[英]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.