C# Take a piece of text at a time in a textbox

66 views Asked by At

I have a textbox(textBox2) where are the email: [email protected],[email protected],[email protected],etc..

I have a function that sends an email:

private void button1_Click(object sender, EventArgs e)
{
    var mail = new MailMessage();
    var smtpServer = new SmtpClient(textBox5.Text);
    mail.From = new MailAddress(textBox1.Text);
    mail.To.Add(textBox2.Text);
    mail.Subject = textBox6.Text;
    mail.Body = textBox7.Text;
    mail.IsBodyHtml = checkBox1.Checked;
    mail.Attachments.Add(new Attachment(textBox9.Text));
    var x = int.Parse(textBox8.Text);
    smtpServer.Port = x;
    smtpServer.Credentials = new System.Net.NetworkCredential(textBox3.Text, textBox4.Text);
    smtpServer.EnableSsl = checkBox2.Checked;
    smtpServer.Send(mail);
}

I want you send an email to each email separately. That is, when I press the button1 to take him an email at a time and send the email until you end up. How can I do?

2

There are 2 answers

0
juharr On BEST ANSWER

If you just don't want all the recipients to see the other addresses you could just use the blind carbon copy instead

mail.Bcc.Add(textBox2.Text);

If you really do want to send the same email multiple times you can just split the addresses on the comma and pass them to the code you already have in a separate method.

private void button1_Click(object sender, EventArgs e)
{
    foreach(var address in textBox2.Text.Split(","))
        SendMessage(address);
}

private void SendMessage(string address)
{
    var mail = new MailMessage();
    var smtpServer = new SmtpClient(textBox5.Text);
    mail.From = new MailAddress(textBox1.Text);
    mail.To.Add(address);
    mail.Subject = textBox6.Text;
    mail.Body = textBox7.Text;
    mail.IsBodyHtml = checkBox1.Checked;
    mail.Attachments.Add(new Attachment(textBox9.Text));
    var x = int.Parse(textBox8.Text);
    smtpServer.Port = x;
    smtpServer.Credentials = new System.Net.NetworkCredential(textBox3.Text, textBox4.Text);
    smtpServer.EnableSsl = checkBox2.Checked;
    smtpServer.Send(mail);
}
0
NicoRiff On

Try this code:

string emailList = "[email protected],[email protected],[email protected]";
string[] emails = emailList.Split(","); // replace this text with your source :)

foreach(string s in emails)
{
var mail = new MailMessage();
            var smtpServer = new SmtpClient(textBox5.Text);
            mail.From = new MailAddress(textBox1.Text);
            mail.To.Add(s);
            mail.Subject = textBox6.Text;
            mail.Body = textBox7.Text;
            mail.IsBodyHtml = checkBox1.Checked;
            mail.Attachments.Add(new Attachment(textBox9.Text));
            var x = int.Parse(textBox8.Text);
            smtpServer.Port = x;
            smtpServer.Credentials = new System.Net.NetworkCredential(textBox3.Text, textBox4.Text);
            smtpServer.EnableSsl = checkBox2.Checked;
            smtpServer.Send(mail);
}