How can I programatically send email via Outlook?

时间:2018-03-25 21:13:45

标签: .net email smtpclient

What I want to do is similar to this question. However that solution uses Settings.Default.* which as best as I can tell doesn't exist.

For a Windows Forms (C#) app, how can I send an email usign the local email client and credentials so I don't have to prompt the user for anything. I definitely don't want to ask the user for their password (and more to the point then have to save that as this will be for a service sending scheduled emails).

thanks - dave

1 个答案:

答案 0 :(得分:0)

您可以在App.config中添加以下配置

<system.net>
<mailSettings>
  <smtp from="donotreply@yourCompany.com" deliveryMethod="Network">
    <network host="mail.yourCompany.com" userName="sender@yourCompany.com" password="yourPassword" port="26" />
  </smtp>
</mailSettings>
</system.net>

然后,在Send方法中,使用SMTP客户端的参数较少的构造函数。您的发送方法将变成这样的

 public void Send(IEnumerable<string> to, string subject, string message)
    {
        var client = new SmtpClient(); 
        var mailMessage = new MailMessage();
        mailMessage.IsBodyHtml = true;
        mailMessage.Bcc.AddRange(to.Select(email => new MailAddress(email)));          
        mailMessage.Subject = subject;
        mailMessage.Body = message;
        client.Send(mailMessage);
    }

如果在配置中存储密码是一个问题,那么您只需加密它并在您的应用程序代码中使用解密器。

相关问题