通过C#通过Google Apps帐户发送电子邮件

时间:2022-10-25 18:15:08

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:

我有一个标准的Google Apps帐户。我已通过Google Apps设置了自定义域名。当我使用Gmail界面时,我可以通过Google Apps成功发送和接收电子邮件。但是,我想通过代码发送电子邮件。为了尝试这个,我一直在尝试以下代码:

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

When the Send method is reached, an Exception is thrown that states:

到达Send方法时,抛出异常,指出:

"The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required."

“SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应为:5.5.1需要身份验证。”

How do I send emails through my custom domain via Google?

如何通过Google通过我的自定义域发送电子邮件?

Thanks!

5 个解决方案

#1


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.

无需对代码中的所有smtp设置进行硬编码。把它们放在web.config中。这样,您可以根据需要加密这些设置,并在不重新编译应用程序的情况下即时更改它们。

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

End when you send email just enable SSL on your SmtpClient:

发送电子邮件时结束只需在SmtpClient上启用SSL:

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

Make sure that you're sending email from the same email address with which you're trying to authenticate at Gmail.

确保您从与Gmail尝试进行身份验证的电子邮件地址发送电子邮件。

Note: Starting with .NET 4.0 you can insert enableSsl="true" into web.config as opposed to setting it in code.

注意:从.NET 4.0开始,您可以将enableSsl =“true”插入到web.config中,而不是在代码中设置它。

#2


This is what I use in WPF 4

这就是我在WPF 4中使用的内容

SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("sender_email@domain.tld", "P@$$w0rD");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;

try {
    MailAddress
        maFrom = new MailAddress("sender_email@domain.tld", "Sender's Name", Encoding.UTF8),
        maTo = new MailAddress("recipient_email@domain2.tld", "Recipient's Name", Encoding.UTF8);
    MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
    mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
    mmsg.BodyEncoding = Encoding.UTF8;
    mmsg.IsBodyHtml = true;
    mmsg.Subject = "Some Other Text as Subject";
    mmsg.SubjectEncoding = Encoding.UTF8;

    client.Send(mmsg);
    MessageBox.Show("Done");
} catch (Exception ex) {
    MessageBox.Show(ex.ToString(), ex.Message);
    //throw;
}

Watch for Firewalls and Anti-Viruses. These creepy things tend to block applications sending email. I use McAfee Enterprise and I have to add the executable name (like Bazar.* for both Bazar.exe and Bazar.vshost.exe) to be able to send emails...

注意防火墙和反病毒。这些令人毛骨悚然的东西往往会阻止应用程我使用McAfee Enterprise,我必须添加可执行文件名(如Bazar.exe和Bazar.vshost.exe的Bazar。*)才能发送电子邮件...

#3


change the port to 465

将端口更改为465

#4


There is not need to do anything. Just login in your current account first time and follow instructions.

没有必要做任何事情。只需首次登录您当前的帐户并按照说明操作即可。

Your problem will resolve. It occur because you had created the account in google apps but did not login. Just login and follow the instructions and try.

你的问题会解决。之所以出现这种情况,是因为您在Google应用中创建了该帐户但未登录。只需登录并按照说明进行操作即可。

#5


My code is connecting to smtp.google.com using TLS on Port=587 (SSL should be port 465) but still needs EnableSsl=true

我的代码使用Port = 587上的TLS(SSL应该是端口465)连接到smtp.google.com但仍需要EnableSsl = true

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = "INSERT EMAIL";
credentials.Password = "INSERT PASSWORD";
smtp.Credentials = credentials;

MailAddress addressFrom = new MailAddress(credentials.UserName);
MailAddress addressTo = new MailAddress("INSERT RECIPIENT");
MailMessage msg = new MailMessage(addressFrom, addressTo);
msg.Subject = "SUBJECT"
msg.Body = "BODY";

smtp.Send(msg);

Notice these important prerequisites on your G SUITE account

请注意您的G SUITE帐户中的这些重要先决条件

  • Ensure that the username you use has cleared the CAPTCHA word verification test that appears when you first sign in.
  • 确保您使用的用户名已清除首次登录时显示的CAPTCHA字验证测试。

  • Ensure that the account has a secure password - https://support.google.com/accounts/answer/32040
  • 确保该帐户具有安全密码 - https://support.google.com/accounts/answer/32040

  • Make sure that Less secure apps is enabled for the desired account- https://support.google.com/a/answer/6260879
  • 确保为所需帐户启用安全性较低的应用程序 - https://support.google.com/a/answer/6260879

#1


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.

无需对代码中的所有smtp设置进行硬编码。把它们放在web.config中。这样,您可以根据需要加密这些设置,并在不重新编译应用程序的情况下即时更改它们。

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

End when you send email just enable SSL on your SmtpClient:

发送电子邮件时结束只需在SmtpClient上启用SSL:

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

Make sure that you're sending email from the same email address with which you're trying to authenticate at Gmail.

确保您从与Gmail尝试进行身份验证的电子邮件地址发送电子邮件。

Note: Starting with .NET 4.0 you can insert enableSsl="true" into web.config as opposed to setting it in code.

注意:从.NET 4.0开始,您可以将enableSsl =“true”插入到web.config中,而不是在代码中设置它。

#2


This is what I use in WPF 4

这就是我在WPF 4中使用的内容

SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("sender_email@domain.tld", "P@$$w0rD");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;

try {
    MailAddress
        maFrom = new MailAddress("sender_email@domain.tld", "Sender's Name", Encoding.UTF8),
        maTo = new MailAddress("recipient_email@domain2.tld", "Recipient's Name", Encoding.UTF8);
    MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
    mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
    mmsg.BodyEncoding = Encoding.UTF8;
    mmsg.IsBodyHtml = true;
    mmsg.Subject = "Some Other Text as Subject";
    mmsg.SubjectEncoding = Encoding.UTF8;

    client.Send(mmsg);
    MessageBox.Show("Done");
} catch (Exception ex) {
    MessageBox.Show(ex.ToString(), ex.Message);
    //throw;
}

Watch for Firewalls and Anti-Viruses. These creepy things tend to block applications sending email. I use McAfee Enterprise and I have to add the executable name (like Bazar.* for both Bazar.exe and Bazar.vshost.exe) to be able to send emails...

注意防火墙和反病毒。这些令人毛骨悚然的东西往往会阻止应用程我使用McAfee Enterprise,我必须添加可执行文件名(如Bazar.exe和Bazar.vshost.exe的Bazar。*)才能发送电子邮件...

#3


change the port to 465

将端口更改为465

#4


There is not need to do anything. Just login in your current account first time and follow instructions.

没有必要做任何事情。只需首次登录您当前的帐户并按照说明操作即可。

Your problem will resolve. It occur because you had created the account in google apps but did not login. Just login and follow the instructions and try.

你的问题会解决。之所以出现这种情况,是因为您在Google应用中创建了该帐户但未登录。只需登录并按照说明进行操作即可。

#5


My code is connecting to smtp.google.com using TLS on Port=587 (SSL should be port 465) but still needs EnableSsl=true

我的代码使用Port = 587上的TLS(SSL应该是端口465)连接到smtp.google.com但仍需要EnableSsl = true

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = "INSERT EMAIL";
credentials.Password = "INSERT PASSWORD";
smtp.Credentials = credentials;

MailAddress addressFrom = new MailAddress(credentials.UserName);
MailAddress addressTo = new MailAddress("INSERT RECIPIENT");
MailMessage msg = new MailMessage(addressFrom, addressTo);
msg.Subject = "SUBJECT"
msg.Body = "BODY";

smtp.Send(msg);

Notice these important prerequisites on your G SUITE account

请注意您的G SUITE帐户中的这些重要先决条件

  • Ensure that the username you use has cleared the CAPTCHA word verification test that appears when you first sign in.
  • 确保您使用的用户名已清除首次登录时显示的CAPTCHA字验证测试。

  • Ensure that the account has a secure password - https://support.google.com/accounts/answer/32040
  • 确保该帐户具有安全密码 - https://support.google.com/accounts/answer/32040

  • Make sure that Less secure apps is enabled for the desired account- https://support.google.com/a/answer/6260879
  • 确保为所需帐户启用安全性较低的应用程序 - https://support.google.com/a/answer/6260879