问题描述
我有一个标准的 Google Apps 帐户.我已经通过 Google Apps 设置了一个自定义域.使用 Gmail 界面时,我可以通过 Google Apps 成功发送和接收电子邮件.但是,我想通过代码发送电子邮件.为了尝试这个,我一直在尝试以下代码:
I have a standard Google Apps account. I have setup a custom domain through Google Apps. I am able to send and receive emails successfully through Google Apps when I use the Gmail interface. However, I want to send an email via code. In order to attempt this, I have been trying the following code:
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("someone@somewhere.com");
mailMessage.Subject = "Test";
mailMessage.Body = "<html><body>This is a test</body></html>";
mailMessage.IsBodyHtml = true;
// Create the credentials to login to the gmail account associated with my custom domain
string sendEmailsFrom = "emailAddress@mydomain.com";
string sendEmailsFromPassword = "password";
NetworkCredential cred = new NetworkCredential(sendEmailsFrom, sendEmailsFromPassword);
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mailClient.EnableSsl = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.UseDefaultCredentials = false;
mailClient.Timeout = 20000;
mailClient.Credentials = cred;
mailClient.Send(mailMessage);
当到达 Send 方法时,抛出一个异常状态:
When the Send method is reached, an Exception is thrown that states:
"SMTP 服务器需要一个安全的连接或客户端没有认证.服务器响应是:5.5.1 需要身份验证."
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."
如何通过 Google 通过我的自定义域发送电子邮件?
How do I send emails through my custom domain via Google?
谢谢!
推荐答案
无需在代码中硬编码所有 smtp 设置.将它们放在 web.config 中.这样,您可以在需要时加密这些设置并即时更改它们,而无需重新编译您的应用程序.
There is no need to hardcode all smtp settings in your code. Put them in web.config instead. This way you can encrypt these settings if needed and change them on the fly without recompiling your application.
<configuration>
<system.net>
<mailSettings>
<smtp from="example@domain.com" deliveryMethod="Network">
<network host="smtp.gmail.com" port="587"
userName="example@domain.com" password="password"/>
</smtp>
</mailSettings>
</system.net>
</configuration>
在您发送电子邮件时结束,只需在您的 SmtpClient 上启用 SSL:
End when you send email just enable SSL on your SmtpClient:
var message = new MailMessage("navin@php.net");
// here is an important part:
message.From = new MailAddress("example@domain.com", "Mailer");
// it's superfluous part here since from address is defined in .config file
// in my example. But since you don't use .config file, you will need it.
var client = new SmtpClient();
client.EnableSsl = true;
client.Send(message);
确保您发送的电子邮件地址与您在 Gmail 中尝试进行身份验证时使用的电子邮件地址相同.
Make sure that you're sending email from the same email address with which you're trying to authenticate at Gmail.
注意:从 .NET 4.0 开始,您可以将 enableSsl="true" 插入 web.config,而不是在代码中进行设置.
Note: Starting with .NET 4.0 you can insert enableSsl="true" into web.config as opposed to setting it in code.
这篇关于通过 Google Apps 帐户通过 C# 发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!