无法使用ASP.NET中的Gmail SMTP服务器发送电子邮件? [英] Not able to send an email using Gmail SMTP server in ASP.NET?

查看:70
本文介绍了无法使用ASP.NET中的Gmail SMTP服务器发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我使用以下代码使用gmail SMTP服务器发送电子邮件。但是我无法发送电子邮件。请查看我的代码并尽早帮助我。



Hi ,
I am using the below code for sending email using gmail SMTP server. But i am not able to send an email.Please review my code and help me as early as possible.

MailMessage mail = new MailMessage();
mail.From = new MailAddress("from gmail emailid");
mail.To.Add("to gmail emailid");
mail.IsBodyHtml = true;
mail.Subject = "Email Sent";
mail.Body = "Mail Done";

SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new System.Net.NetworkCredential(my gmail id", "my gmail password");
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);

推荐答案

一定要使用System.Net.Mail,而不是不推荐使用的System.Web.Mail。使用System.Web.Mail执行SSL是一堆乱糟糟的扩展。



Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.

using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
           {
               Host = "smtp.gmail.com",
               Port = 587,
               EnableSsl = true,
               DeliveryMethod = SmtpDeliveryMethod.Network,
               UseDefaultCredentials = false,
               Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
           };
using (var message = new MailMessage(fromAddress, toAddress)
                     {
                         Subject = subject,
                         Body = body
                     })
{
    smtp.Send(message);
}


这篇关于无法使用ASP.NET中的Gmail SMTP服务器发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆