使用 Gmail 凭据在 ASP.NET 中发送电子邮件






3.54/5 (26投票s)
本文包含使用 Gmail 帐户发送电子邮件的代码。
引言
作为 ASP.NET Web 开发者,我们经常需要在网站中包含一个电子邮件发送模块。当我完成大学三年级项目时,我的 Web 项目也有同样的需求。我不得不浏览很多网站和博客才能找到解决方案。使用本文包含的类文件,您可以输入您的 Gmail 帐户凭据来发送电子邮件。
背景
请确保使用正确的参数实例化该类的实例。
Using the Code
要使用此类,请将此类添加到网站的 App_Code 文件夹中。然后,创建一个网页来获取发送邮件所需的的用户输入,例如:收件人、主题和消息。然后,根据需要编辑用户名和密码文件。在这里,为了允许用户发送邮件,请确保使用网站获取用户名和密码。然后,添加两个变量将用户名和密码传递给应用程序。
编辑 sendMail()
如下
public static void sendMail(string to, string from, string subject,
string body,string username, string password)
{
///Smtp config
SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
// Edit password and username
client.Credentials = new NetworkCredential(""+username+"@gmail.com", password);
client.EnableSsl = true;
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] =
""+username+"@gmail.com";
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = password;
如果您不允许每个用户发送电子邮件,而只允许某些用户发送,那么您可以为所有发件人使用一个通用的电子邮件地址,例如 admin@obrs.com。然后,您不需要更改任何其他方法定义,但请确保更改用户名和密码。
client.Credentials = new NetworkCredential("USERNAME@gmil.com", "PASSWORD");
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] =
"USERNAME@gmail.com";
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = "PASSWORD";
关注点
这个类的一个主要特性是它有一个备用方案,以防万一。邮件发送方法是 sendMail()
,但如果它失败,它将调用一个替代邮件发送方法 SendMailAlt()
,使用适当的属性。
但是,第二种方法不允许我们发送附件。因此,不要允许用户将附件添加到任何方法中。