首页 > 解决方案 > 使用 C# 发送电子邮件

问题描述

我正在尝试使用 C# 发送电子邮件,但出现以下错误。

邮箱不可用。服务器响应是:中继访问被拒绝。请认证。

我不确定为什么会收到此错误。在这里,我使用 smtp2go 第三方发送这封邮件。

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);

标签: c#smtpclient

解决方案


I've tried your code and it work fine.
But in my case, to use the smtp server, from(email address of sender) must use the same domain to authenticate.(but gmail is available to this Send emails from a different address or alias)

So, If your SMTP server connect to smtp2go.com, try as below.

SmtpClient SmtpServer = new SmtpClient("mail.smtp2go.com");
mail.From = new MailAddress("myemail@smtp2go.com");

Or if you need to use service of smtp2go, it would be better use rest API.


Here is updated by your comment when using gmail.

Gmail required secure app access. that's a reason why code is not work.
So, there is two options for this.

1. Update your gmail account security

(origin idea from here : C# - 이메일 발송방법)

Go to here and turn on "Less secure app access". after doing this your code will work.(it works)

2. Using "Google API Client Library for .NET."

I think this is not so easy, check this out, I found an answer related with this here


推荐阅读