gpt4 book ai didi

c# - 使用 C# 从 g-mail 主机发送电子邮件到五个不同的电子邮件帐户

转载 作者:行者123 更新时间:2023-11-30 22:14:23 24 4
gpt4 key购买 nike

我想向 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);


}



}
}

最佳答案

您将 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);


}

关于c# - 使用 C# 从 g-mail 主机发送电子邮件到五个不同的电子邮件帐户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18520996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com