Sending mail using Gmail
开发者_JAVA百科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;
}
}
The code seems ok, but still not working, I am not able to figure out why? any other way to use gmail's smtp to send mail.
try
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");
If the UseDefaultCredentials
property is set to false
, then the value set in the Credentials
property will be used for the credentials when connecting to the server. Here you set UseDefaultCredentials
as true
then it will neglect credentials you given.
Please try with Port 25. It's working for me. Also remove setting of UseDefaultCredentials.
Update : Port 587 also working for me. So I think UseDefaultCredentials is only problem in your code. it should be set to 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;
}
}
精彩评论