string mailServerName = "smtp.qq.com"; //发送邮件的SMTP服务器
string mailFrom = "[email protected]"; //发件人邮箱(用126的邮件服务器,就必须用126邮箱的用户名)
string mailTo = "[email protected]"; //收件人邮箱
string subject = "用代码方式发送邮件";//邮件主题
string body = "这里是邮件正文了"; //邮件正文
using (MailMessage message = new MailMessage(mailFrom, mailTo, subject, body))
{
//SmtpClient是发送邮件的主体,这个构造函数是告知SmtpClient发送邮件时使用哪个SMTP服务器
SmtpClient mailClient = new SmtpClient(mailServerName);
//将认证实例赋予mailClient,也就是访问SMTP服务器的用户名和密码
mailClient.Credentials = new NetworkCredential("456862", "asdfasf45");
//最终的发送方法
mailClient.Send(message);
}
报错 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败
在本机可以ping通这个服务器的
mailClient.Credentials = new NetworkCredential("456862", "asdfasf45");这两个不一致吧。
MailMessage mail = new MailMessage();
mail.To = "[email protected] ";
mail.From = "[email protected] ";
mail.Subject = "this is a test email. ";
mail.Body = "Some text goes here ";
mail.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate ", "1 ");
mail.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendusername ","my_username_here ");
mail.Fields.Add( "http://schemas.microsoft.com/cdo/configuration/sendpassword ", "super_secret ");
SmtpMail.SmtpServer = "mail.mycompany.com ";
SmtpMail.Send( mail );
如果不成功说面是smtp的问题
成功的话,再把防火墙关了试下,我以前碰到过类似问题,后来禁用邮件防护就好了
/// <summary>
/// 发送email
/// </summary>
/// <param name="Recevie">接受人地址</param>
/// <param name="Send">发件人地址</param>
/// <param name="SendPwd">发件人密码</param>
/// <param name="Title">邮件标题</param>
/// <param name="Body">邮件内容</param>
/// <param name="Server">服务器</param>
/// <returns>bool</returns>
public bool SendUserEmail(string Recevie, string Send, string SendPwd, string Title, string Body, string ServerName)
{
try
{
MailMessage mail = new MailMessage(); //构造message 对象
mail.To.Add(Recevie); //收件人邮箱
mail.From = new MailAddress("" + Send + "", "来自", System.Text.Encoding.UTF8); //发件人地址
mail.Subject = "" + Title + ""; //邮件标题
mail.SubjectEncoding = System.Text.Encoding.UTF8; //标题编码
mail.Body = "" + Body + ""; //邮件正文
mail.BodyEncoding = System.Text.Encoding.UTF8; //正文编码
mail.IsBodyHtml = true;
SmtpClient client = new SmtpClient(); //构建STMP 协议传输对象
client.UseDefaultCredentials = true;
client.Credentials = new NetworkCredential("" + Send + "", "" + SendPwd + "");
//client.Credentials = new System.Net.NetworkCredential("[email protected]", "a123456"); //发件人邮箱,及密码
client.Host = "" + ServerName + "";
client.Port = 25;
try
{
client.Send(mail);
return true;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
catch
{
return false;
}
}