gpt4 book ai didi

c# - 如何发送邮件,邮件正文作为参数并使用线程 - C#

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:26 25 4
gpt4 key购买 nike

我有一个问题,我正在尝试使用像这样的一种结构发送邮件:

private void SendMail()
{

var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mymail@mail.com", "mypassword"),
EnableSsl = true
};
client.Send("mymail@mail.com", "AdressClient@mail.com", "Subject", "Body");
}

好吧,这个结构工作得很好,但会导致我的主程序延迟,因此我想在另一个线程中执行 SendMail 函数,如下所示:

private void ButtonTestSendMail_Click(object sender, EventArgs e)
{
//THREAD
Thread ThreadSendEmail = new Thread(new ThreadStart(this.SendMail));
ThreadSendEmail .IsBackground = true;
ThreadSendEmail .Start();
}


private void SendMail()
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mymail@mail.com", "mypassword"),
EnableSsl = true
};
client.Send("mymail@mail.com", "AdressClient@mail.com", "Subject", "Body");
}

此时我注意到我需要更改邮件的参数,例如 AdressClient@mail.com、主题和正文。

但我不知道怎么做:/

我怎样才能写一个接受参数的线程,像这样:

private void ButtonTestSendMail_Click(object sender, EventArgs e)
{
string Body = "BodyTest";
string AdressMail = "AdressMail@test.com";
string Subject = "SubjectTest";
//THREAD
Thread ThreadSendEmail = new Thread(new ThreadStart(this.SendMail(Body,AdressMail,Subject));
ThreadSendEmail .IsBackground = true;
ThreadSendEmail .Start();
}


private void SendMail(string Body, string Adress, string Subject)
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mymail@mail.com", "mypassword"),
EnableSsl = true
};
client.Send("mymail@mail.com", Adress, Subject, Body);
}

我试过了但没有用,我有一个 MethodName Expected 和一个错误在这一行的通知:

Thread ThreadSendEmail = new Thread(new ThreadStart(this.SendMail(Body,AdressMail,Subject));

如何编写接受参数的线程?谢谢你的帮助!最好的问候!

最佳答案

你快到了:

Thread ThreadSendEmail = new Thread(() => this.SendMail(Body,AdressMail,Subject));

lambda 可以解决问题。您不能直接调用 SendMail,您希望将其作为未调用的函数传递。

请注意,如果您的 ASP.NET 进程回收(可能是因为您正在部署),线程将被粗鲁地中止。邮件将丢失。

关于c# - 如何发送邮件,邮件正文作为参数并使用线程 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15179993/

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