解决.net中使用gmail.com邮箱进行Smtp发送信件时失败的问题

时间:2022-02-12 18:12:11
我经常使用免费的gmail.com邮箱,因为它容量较大,但我们在使用.net编程实现邮件发送时,常会出现我们意想不到的错误。最常见的就是:

(1)The operation has timed out.
(2)出现类似提示:
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first ...."

 出现此类错误的主要原因是:
(1)POP的设置不对;
(2)SmtpClient的UseDefaultCredentials,Credentials,EnableSsl设置不正确所引起。

 首先,需要进入gmail.com邮箱,进行"
转发和 POP/IMAP"的选项设置。如下图:
解决.net中使用gmail.com邮箱进行Smtp发送信件时失败的问题
然后,在你的Smtp程序中设置以下几项即可:
            // 创建 SmtpClient 以发送 Email
            SmtpClient client = new SmtpClient();

            MailMessage message = new MailMessage();

            // 设置发信人的EMAIL地址
            message.From = new MailAddress(fromAddress);

            // 设置收信人的EMAIL地址
            message.To.Add(toAddress);
            // 设置回复的EMAIL地址
            message.ReplyTo = new MailAddress(replyToAddress);

            // 设置抄送的EMAIL地址

            // message.CC.Add(ccAddress);
            // message.Bcc.Add(bccAddress);

            // 设置发信主题及内容

            message.Subject = msgSubject;
            
message.Body = body;
            message.IsBodyHtml = isHtmlBody;
            // 设置SMTP host及端口
            client.Host = "smtp.gmail.com";
            client.Port = 25;
            client.UseDefaultCredentials = false;
            System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(fromAddress, smtpPassword);
            client.Credentials = basicAuthenticationInfo;
            client.EnableSsl = true;
            client.Send(message);

祝程序发送给你带来快乐享受!