- 首先登录Gmail邮箱设置开启IMAP
2. 如果Google账号没有开通两步验证,先开启两步验证
3. 开启两步验证后再开启应用专用密码
4. 生成应用密码
5. 在Gmail应用中可使用该应用密码登录,代码调用发送邮件时也使用该密码(注意:代码中如果用登录密码会有安全验证提示错误,需要用应用密码)
public static void Send(string host,
int port,
bool useSsl,
string fromUserName,
string fromPassword,
string fromName,
string fromAddress,
string toAddress,
string toTitle,
string toBody)
{
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(host);
smtp.Port = 587;
smtp.EnableSsl = true; //开启安全连接。
smtp.Credentials = new NetworkCredential(fromUserName, fromPassword); //创建用户凭证
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //使用网络传送
MailMessage message = new MailMessage(fromAddress, toAddress, toTitle, toBody);
smtp.Send(message); //发送邮件
}