gpt4 book ai didi

c# - 在 C# 中使用无密码的 SMTP 发送电子邮件

转载 作者:行者123 更新时间:2023-11-30 16:45:04 25 4
gpt4 key购买 nike

我有一个使用 ASP.net 和 C# 的 Web 应用程序,一步之内它需要从用户到向带有附件的人发送电子邮件。我的问题是当用户发送电子邮件时我不想把他们的每次用户发送密码。我想发送一封没有发件人密码的电子邮件。有什么方法可以使用 SMTP 做到这一点?这是我的代码示例“并非全部”。当我输入密码时,代码可以正常工作,但没有它,它不起作用,我需要一种无需输入密码即可发送电子邮件的方法,但是同时使用smtp协议(protocol)。

private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.office365.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "my email";
string password = "******";
string emailTo = "receiver mail";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
// mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));

using (SmtpClient smtp = new SmtpClient(smtpAddress,portNumber))
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
MessageBox.Show("message sent");
}
}

最佳答案

我相信这可以很容易地完成,但有一些限制。

看看 MSDN article on configuring SMTP in your config file .

如果您的 SMTP 服务器允许,您的电子邮件对象的发件人地址可能不需要与用于连接到 SMTP 服务器的凭据相同。

因此,设置您的电子邮件对象的发件人地址:

mail.From = new MailAddress(emailFrom);

但是,请使用以下两种方式之一配置您的 smtp 连接:

  1. 将您的应用设置为在有权访问 SMTP 服务器的帐户下运行
  2. 在您的配置中包含 SMTP 服务器的凭据,like this .

然后,做这样的事情:

using (SmtpClient smtp = new SmtpClient())
{
smtp.Send(mail);
}

让配置文件为您设置 SMTP。这也很棒,因为如果您切换服务器,则无需更改任何代码。

请记住要小心配置文件中的任何敏感设置! (又名,不要将它们 checkin 公共(public) github 存储库)

关于c# - 在 C# 中使用无密码的 SMTP 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42845060/

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