当新用户使用asp.net c#在我的网站注册时,如何发送激活电子邮件?我已经尝试了所描述的步骤 this link但我遇到了这个错误:
System.IO.IOException:无法从传输连接中读取数据:net_io_connectionclosed。
是否有解决方案或其他任何方式发送电子邮件?
这是我的代码
using (MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text))
{
mm.Subject = "Account Activation";
string body = "Hello " + txtUsername.Text.Trim() + ",";
body += "<br /><br />Please click the following link to activate your account";
body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
body += "<br /><br />Thanks";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("sender@gmail.com", "<password>");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
建议的副本没有解决问题。我已经在使用端口587了。
答案 0 :(得分:1)
请参阅以下代码:
public static class email_utility
{
public static async Task<bool> send_email(this string body, string subject, string email, int try_count)
{
return await Task.Run(() =>
{
var cli = new SmtpClient();
using (var message = new MailMessage(config.sender_email, email))
{
message.Subject = subject;
message.SubjectEncoding = UTF8Encoding.UTF8;
message.Body = body;
message.BodyEncoding = UTF8Encoding.UTF8;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.Never;
for (var count = 0; count < try_count; ++count)
{
try
{
lock (config.sender_email)
{
cli.Send(message);
return true;
}
}
catch (SmtpFailedRecipientsException)
{
return false;
}
catch (SmtpException)
{
Thread.Sleep(config.send_timeout);
}
}
return false;
}
});
}
}
答案 1 :(得分:1)
试试这个,它完美无缺,您只需要更改var smtp = newSMTPCient之前的字段。
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}