C# 如何使用Gmail 发送邮件

841 阅读1分钟
  1. 首先登录Gmail邮箱设置开启IMAP

image.png
2. 如果Google账号没有开通两步验证,先开启两步验证

image.png
3. 开启两步验证后再开启应用专用密码

image.png
4. 生成应用密码

image.png
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); //发送邮件
        }