【问题标题】:send an email using SMTP without password in C#在 C# 中使用没有密码的 SMTP 发送电子邮件
【发布时间】:2017-08-08 06:36:54
【问题描述】:

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

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");
}
} 

【问题讨论】:

  • 这将需要一个开放的中继,我怀疑这是否已经完成了,原因很明显。

标签: c# email smtp


【解决方案1】:

我相信这很容易实现,但有一些限制。

看看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。这也很棒,因为如果您切换服务器,则无需更改任何代码。

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

【讨论】:

  • 请问,我如何“将您的应用程序设置为在有权访问 SMTP 服务器的帐户下运行”? @SouthShoreAK
猜你喜欢
  • 2018-05-15
  • 2016-04-17
  • 1970-01-01
  • 2019-01-09
  • 2017-02-15
  • 1970-01-01
  • 2021-08-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多