从类发送电子邮件
这种方式可能非常有用,但是,有些人(像我一样)是重复代码的遗骸,就像你在我们身上一样,这意味着我需要在每个我们拥有的项目中创建一个具有相同代码的联系控制器,所以,我觉得这也有帮助
这是我的类,可以在 DLL 或其他任何东西上
public class Emails
{
public static void SendHtmlEmail(string receiverEmail, string subject, string body, bool Ssl = false)
{
//Those are read it from webconfig or appconfig
var client = new SmtpClient(ConfigurationManager.AppSettings["MailServer"], Convert.ToInt16
(ConfigurationManager.AppSettings["MailPort"]))
{
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["MailSender"], ConfigurationManager.AppSettings["MailSenderPassword"]),
EnableSsl = Ssl
};
MailMessage message = new MailMessage();
message.From = new MailAddress(ConfigurationManager.AppSettings["MailSender"]);
message.To.Add(receiverEmail);
// message.To.Add("sgermosen@praysoft.net");
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
client.Send(message);
}
}
就像你看到它会从 webconfig 中读取一样,所以,我们需要配置它,这个配置适用于 Gmail,但是,每个主机都有自己的配置
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="AdminUser" value="sgrysoft@gmail.com" />
<add key="AdminPassWord" value="123456789" />
<add key="SMTPName" value="smtp.gmail.com" />
<add key="SMTPPort" value="587" />
</appSettings>