2

我想向 5 个不同的电子邮件帐户发送电子邮件,每当我激活具有“ ----> 此行”的那些代码行时,我的问题就在以下代码中,它工作正常,但是当我停用这些行时,它会发送五封电子邮件到一个电子邮件帐户,而对其他人没有。

有人知道我的代码有什么问题吗?

namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        Thread t = null;
        MailMessage mailMessage;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
          //textBox1 is recipients email addresses 
            String[] to = textBox1.Text.Split(';');

            foreach (String s in to)
            {
                Object[] array = new Object[2];
                array[0] = (textBox4.Text.ToString());
                array[1] = (s.ToString());
               // MessageBox.Show(s.ToString()); -----> this line 
                t = new Thread(sentEmail);
                t.Start(array);
                //MessageBox.Show("from: " + array[0].ToString()); -----> this line 
               // MessageBox.Show("to: " + array[1].ToString()); ----->this line 
                Thread.Sleep(50);


            }       

        }


        void sentEmail(Object array)
        {
            Object[] o = array as Object[];
            SmtpClient client = new SmtpClient();
            client.EnableSsl = true;
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.Credentials = new NetworkCredential(textBox4.Text, textBox5.Text);
            mailMessage = new MailMessage(new MailAddress(o[0].ToString()), new MailAddress(o[1].ToString()));
            mailMessage.Body = textBox3.Text;
            mailMessage.Subject = textBox2.Text;
            client.Send(mailMessage);


        }



    }
}
4

2 回答 2

2

You're storing the mailMessage as a property of the Form, and the address is getting changed by another thread before it's actually sent. Adding the MessageBox lets one thread finish befiore another one starts. Just change sentMail to create a new MailMessage instead of reusing the existing one and you should be fine:

public partial class Form1 : Form
{
    Thread t = null;
    //MailMessage mailMessage;  <-- take out this line

    void sentEmail(Object array)
    {
        Object[] o = array as Object[];
        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.Credentials = new NetworkCredential(textBox4.Text, textBox5.Text);
        MailMessage mailMessage = new MailMessage(new MailAddress(o[0].ToString()), new MailAddress(o[1].ToString()));  // <-- don't use the Form property
        mailMessage.Body = textBox3.Text;
        mailMessage.Subject = textBox2.Text;
        client.Send(mailMessage);


    }
于 2013-08-29T21:12:35.737 回答
1

您正在重用该mailMessage对象。我怀疑您注释掉的行会减慢处理速度,以至于正确发送 5 条不同的消息/线程完成。当它们不在那里时,您会得到奇怪的行为,因为线程正在访问同一个对象。

打算在这里清理代码,但@D_Stanley 已经涵盖了您。

于 2013-08-29T21:19:13.770 回答