[英]Send email using c#
我正在尝试使用 C# 发送 email 但我遇到了错误。
邮箱不可用。 服务器响应是:中继访问被拒绝。 请认证。
我不确定为什么会收到此错误。 在这里,我使用smtp2go第三方发送这个email。
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail@wraptite.com");
mail.To.Add("test1@gmail.com");
mail.Subject = "Test Email";
mail.Body = "Report";
//Attachment attachment = new Attachment(filename);
//mail.Attachments.Add(attachment);
SmtpServer.Port = 25;
SmtpServer.Credentials = new System.Net.NetworkCredential("me", "password");
//SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
我试过你的代码,它工作正常。
但在我的情况下,要使用 smtp 服务器,来自(发件人的电子邮件地址)必须使用相同的域进行身份验证。(但 gmail 可用于此从不同地址或别名发送电子邮件)
因此,如果您的 SMTP 服务器连接到smtp2go.com
,请尝试以下操作。
SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail@smtp2go.com");
或者如果您需要使用 smtp2go 的服务,最好使用 rest API 。
Gmail 需要安全应用访问。 这就是代码不起作用的原因。
因此,有两种选择。
(源自这里的想法: C# - 이메일 발송방법 )
Go 到这里并turn on
“不太安全的应用程序访问”。 完成此操作后,您的代码将起作用。(有效)
我认为这不是那么容易,检查一下,我在这里找到了与此相关的答案
#region SendMail
//Mail Setting
string EmailSubject = "EmailSubject";
string EmailBody = "EmailBody";
try
{
string FromAddress = "abc@gmail.com";
string EmailList = "abc1@gmail.com";
string EmailServer = "ipofemailserver";
using (var theMessage = new MailMessage(FromAddress, EmailList))
{
// Construct the alternate body as HTML.
string body = "EmailBody";
ContentType mimeType = new System.Net.Mime.ContentType("text/html");
// Add the alternate body to the message.
AlternateView alternate = AlternateView.CreateAlternateViewFromString(body, mimeType);
theMessage.AlternateViews.Add(alternate);
theMessage.Subject = EmailSubject;
theMessage.IsBodyHtml = true;
SmtpClient theSmtpServer = new SmtpClient();
theSmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
theSmtpServer.Host = EmailServer;
theSmtpServer.Send(theMessage);
}
}
catch (Exception ex)
{
string AppPath = AppDomain.CurrentDomain.BaseDirectory;
string ErrorPath = AppDomain.CurrentDomain.BaseDirectory + "File\\Error\\";
string OutFileTime = DateTime.Now.ToString("yyyyMMdd");
using (StreamWriter sw = new StreamWriter(ErrorPath + OutFileTime + ".txt", true, System.Text.Encoding.UTF8))
{
sw.WriteLine(DateTime.Now.ToString() + ":");
sw.WriteLine(ex.ToString());
sw.Close();
}
}
#endregion
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.