我正在尝试使用SMTP在C#上发送电子邮件但我收到错误"发送邮件失败" 我想问下面的代码是否正确
private void SendMail()
{
MailMessage mail = new MailMessage();
SmtpClient mailClient = new SmtpClient();
mail.From = new MailAddress(MailConst.From);
mail.To.Add(new MailAddress("recepient@gmail.com"));
mail.Subject = "Test";
mail.Body = "This is a test";
mailClient.Host = MailConst.SmtpServer;
mailClient.UseDefaultCredentials = false;
mailClient.Port = 465;
mailClient.EnableSsl = true;
mailClient.Credentials = new NetworkCredential(MailConst.Username, MailConst.Password);
try
{
mailClient.Send(mail);
}
catch(Exception ex)
{
WriteErrorOutput(ex.Message);
}
}
public class MailConst
{
public static string Username = "user";
public static string Password = "pass";
public const string SmtpServer = "smtp.gmail.com";
public static string From = Username + "@gmail.com";
}
我继续获得例外"未能发送消息"。
当我尝试打开异常时,看看它说错了什么" Command' Debug.QuickWatch'不可用。"
感谢您回答我的问题所花的时间和帮助。
谢谢。
编辑:
终于能够看到内部异常,好像我的连接被拒绝了。 与我们的网络管理员联系,他说我们的网络阻止了Gmail SMTP。
感谢帮助人员。
答案 0 :(得分:1)
我认为我们需要检查连接
要在计算机上的Windows上运行telnet并进行测试:
1.Open the Start menu, and select Run.
2.Enter command in the Open: field, and click OK.
3.Enter 'telnet smtp.gmail.com 465,' and hit Enter, or enter 'telnet smtp.gmail.com 587' instead.
答案 1 :(得分:-1)
试试这个..
private void SendMail()
{
MailMessage mail = new MailMessage();
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mail.From = new MailAddress(MailConst.From);
mail.To.Add(new MailAddress("recepient@gmail.com"));
mail.Subject = "Test";
mail.Body = "This is a test";
mailClient.EnableSsl = true;
mailClient.Credentials = new NetworkCredential(MailConst.Username, MailConst.Password);
try
{
mailClient.Send(mail);
}
catch(Exception ex)
{
WriteErrorOutput(ex.Message);
}
}