我想向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);
}
}
}
答案 0 :(得分:2)
您将mailMessage
存储为表单的属性,并且在实际发送之前,地址将被另一个线程更改。添加MessageBox
让一个线程完成另一个线程开始。只需更改sentMail
即可创建新的MailMessage
,而不是重复使用现有的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);
}
,您应该没问题:
{{1}}
答案 1 :(得分:1)
您正在重用mailMessage
对象。我怀疑你注释掉的行减慢了处理速度,以便正确发送5条不同的消息/线程完成。当它们不在那里时,你会得到奇怪的行为,因为线程正在访问同一个对象。
这里要清理代码,但@D_Stanley已经覆盖了你。