.net邮件发送在本地测试都可以正常发邮件,,一发布的服务器上后就出现发送失败(测试的邮箱和我到本地的测试通过的邮箱一样);分别用过126,163,sina,qq邮箱,在本地测试通过,发布到网上后无法发送成功,捕到异常:
System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 123.125.50.133:25
这里的红色ip是邮箱服务器的地址,后面的25为端口号;
看我代码
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="fromEmail">发件人</param>
/// <param name="fromPsaaWord">发件人密码</param>
/// <param name="toEmail">收件人</param>
/// <param name="subject">主题</param>
/// <param name="body">内容</param>
/// <param name="attachmentsPath">附件(如果没有写为null)</param>
/// <returns></returns>
public bool SendReady(string fromEmail, string fromPsaaWord, string toEmail, string subject, string body, string[] attachmentsPath)
{
bool Success = true;
//验证合法邮箱的表达式,正确时返回true
if (!Regex.IsMatch(fromEmail, @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
{
//邮箱不合法
//MessageBox("邮箱不合法");
Success = false;
}
if (!Regex.IsMatch(toEmail, @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"))
{
Success = false;
}
if (subject.Trim() == "")
{
// MessageBox("请填写主题");
Success = false;
}
if (body.Trim() == "")
{
// MessageBox("请填写内容");
Success = false;
}
else
{
MailAddress from = new MailAddress(fromEmail);
//收件人地址
MailAddress to = new MailAddress(toEmail);
//邮件主题、内容
MailMessage message = new MailMessage(from, to);
//主题
message.Subject = subject;
message.SubjectEncoding = System.Text.Encoding.UTF8;
//内容
message.Body = body;
message.BodyEncoding = System.Text.Encoding.UTF8;
//在有附件的情况下添加附件
try
{
if (attachmentsPath != null && attachmentsPath.Length > 0)
{
Attachment attachFile = null;
foreach (string path in attachmentsPath)
{
attachFile = new Attachment(path);
message.Attachments.Add(attachFile);
}
}
}
catch (Exception err)
{
// MessageBox("在添加附件时有错误");
Success = false;
//throw new Exception("在添加附件时有错误:" + err);
}
try
{
//大部分邮件服务器均加smtp.前缀
SmtpClient client = new SmtpClient("smtp." + from.Host);
//不使用默认凭证,注意此句必须放在client.Credentials的上面
client.UseDefaultCredentials = false;
//指定用户名、密码
client.Credentials = new NetworkCredential(from.Address, fromPsaaWord);
//邮件通过网络发送到服务器
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.Send(message);
}
catch (Exception e)
{
Success = false;
throw new Exception("系统繁忙,发送失败!");
}
finally
{
//及时释放占用的资源
message.Dispose();
}
}
catch (SmtpException err)
{
Success = false;
////如果错误原因是没有找到服务器,则尝试不加smtp.前缀的服务器
//if (err.StatusCode == SmtpStatusCode.GeneralFailure)
//{
// try
// {
// //有些邮件服务器不加smtp.前缀
// SmtpClient client = new SmtpClient(from.Host);
// SendMail(client, from, fromPsaaWord, to, message)//发送;
// }
// catch (SmtpException)
// { }
//}
//else
//{ }
}
}
return Success;
}
到网上用过不同的代码,包括.net 1.1的代码!都是出现上面我说的情况,在本地测试成功,发到服务器上失败!我防火墙关了,没有安杀毒软件。。
我记得好像要把系统的smtp服务安装并启动才行,web.config配置正确的smtp项
你发送附件了?
现在解决了吗?我也遇到这样的问题了@!