i wrote the method as below i got the error as The specified string is not in the form required for an e-mail address. pls help me
SendMail("xyz@gmail.com","hi","heloo");
public bool SendMail(string toMailAddress, string mailSubject, string mailMessage)
{
string smtphost ="smtp.gmail.com";
int smtpport = 100;
string smtpuser ="xyz";
string smtppwd = "xyz";
SmtpClient client = null;
string MessageBody = string.Empty;
try
{
message = new MailMessage();
message.From = new MailAddress(开发者_如何学编程smtpuser);
message.To.Add(toMailAddress);
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = mailSubject;
message.Body = mailMessage.ToString();
message.IsBodyHtml = true;
client = new SmtpClient();
client.Host = smtphost;
client.Port = smtpport;
client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd);
client.Send(message);
}
catch (Exception ex)
{
string x = ex.Message;
}
return true;
}
Your "from" user must be in the form of a valid email address.
message.From = new MailAddress(smtpuser);
Also, you will need to use the MailAddress constructor for the .To property as well.
Try, with port as 25 and IsSSLEnabled as true since gmail server is SSL enabled
Make sure the toMailAddress, and smtpuser are valid email address. Try, Using smtpport = 587; provided by Gmail for Outgoing Mails (SMTP). Hope this will make it work fine. Please list out the errors you encounter.
This code will work. What i have done are
- proper smtphost
- proper smtpport - 587
- Enable SSL
- set UseDefaultCredentials to false before setting the credentials
- set DeliveryMethod
public static bool SendMail(string toMailAddress, string mailSubject, string mailMessage) { string smtphost = "smtp.gmail.com"; int smtpport = 587; string smtpuser = "youremail@gmail.com"; string smtppwd = "password"; SmtpClient client = null; string MessageBody = string.Empty; try { var message = new MailMessage(); message.From = new MailAddress(smtpuser); message.To.Add(toMailAddress); message.BodyEncoding = System.Text.Encoding.UTF8; message.Subject = mailSubject; message.Body = mailMessage.ToString(); message.IsBodyHtml = true; client = new SmtpClient(); client.Host = smtphost; client.EnableSsl = true; client.Port = smtpport; client.UseDefaultCredentials = false; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new System.Net.NetworkCredential(smtpuser, smtppwd); client.Send(message); } catch (Exception ex) { string x = ex.InnerException.Message; Console.WriteLine(x); } return true; }
精彩评论