public static bool SendMail(string toList, string from, string ccList, string subject, string body)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
smtpClient.Timeout = 30000;
smtpClient.Host = "smtp.gmail.com"; // We use gmail as our smtp client
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassword");
smtpClient.Send(message);
return true;
}
catch (Exception ex)
{
return false;
}
}
代码似乎没问题,但仍然无法正常工作,我无法找出原因? 使用gmail的smtp发送邮件的任何其他方式。
答案 0 :(得分:4)
尝试
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
如果UseDefaultCredentials
属性设置为false
,则在连接到服务器时,Credentials
属性中设置的值将用于凭据。在这里,您将UseDefaultCredentials
设置为true
,然后忽略您提供的凭据。
答案 1 :(得分:3)
请尝试25号端口。它对我有用。同时删除UseDefaultCredentials的设置。
更新:端口587也适合我。所以我认为UseDefaultCredentials只是代码中的问题。它应该设置为false。
public static void SendMail(string ToMail, string FromMail, string Cc, string Body, string Subject)
{
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 25);
MailMessage mailmsg = new MailMessage();
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("email","password");
mailmsg.From = new MailAddress(FromMail);
mailmsg.To.Add(ToMail);
if (Cc != "")
{
mailmsg.CC.Add(Cc);
}
mailmsg.Body = Body;
mailmsg.Subject = Subject;
mailmsg.IsBodyHtml = true;
mailmsg.Priority = MailPriority.High;
try
{
smtp.Timeout = 500000;
smtp.Send(mailmsg);
mailmsg.Dispose();
}
catch (Exception ex)
{
throw ex;
}
}