简体   繁体   English

通过 Gmail 在 .NET 中发送电子邮件

[英]Sending email in .NET through Gmail

Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account.我没有依赖主机来发送电子邮件,而是考虑使用我的Gmail帐户发送电子邮件。 The emails are personalized emails to the bands I play on my show.这些电子邮件是发送给我在节目中演奏的乐队的个性化电子邮件。

Is it possible to do it?有可能做到吗?

Be sure to use System.Net.Mail , not the deprecated System.Web.Mail .请务必使用System.Net.Mail ,而不是已弃用的System.Web.Mail Doing SSL with System.Web.Mail is a gross mess of hacky extensions.使用System.Web.Mail进行 SSL 是一堆乱七八糟的扩展。

using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.此外,转到Google 帐户 > 安全页面并查看登录 Google > 两步验证设置。

  • If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification.如果已启用,则您必须生成一个密码,允许 .NET 绕过两步验证。 To do this, click on Signing in to Google > App passwords , select app = Mail, and device = Windows Computer, and finally generate the password.为此,请点击Signing in to Google > App passwords ,选择 app = Mail 和 device = Windows Computer,最后生成密码。 Use the generated password in the fromPassword constant instead of your standard Gmail password.fromPassword常量中使用生成的密码,而不是您的标准 Gmail 密码。
  • If it is disabled, then you have to turn on Less secure app access , which is not recommended!如果它被禁用,那么您必须打开不太安全的应用程序访问,不推荐! So better enable the 2-Step verification.所以最好启用两步验证。

The above answer doesn't work.上面的答案不起作用。 You have to set DeliveryMethod = SmtpDeliveryMethod.Network or it will come back with a " client was not authenticated " error.您必须设置DeliveryMethod = SmtpDeliveryMethod.Network否则它将返回“客户端未通过身份验证”错误。 Also it's always a good idea to put a timeout.此外,设置超时总是一个好主意。

Revised code:修改后的代码:

using System.Net.Mail;
using System.Net;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@yahoo.com", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
    Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}

Edit 2022 Starting May 30, 2022, ​​Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.编辑 2022从 2022 年 5 月 30 日开始, Google 将不再支持使用第三方应用或设备,这些应用或设备要求您仅使用您的用户名和密码登录您的 Google 帐户。 But you still can send E-Mail via your gmail account.但是您仍然可以通过您的 gmail 帐户发送电子邮件。

  1. Go to https://myaccount.google.com/security and turn on two step verification .转到https://myaccount.google.com/security并打开两步验证 Confirm your account by phone if needed.如果需要,请通过电话确认您的帐户。
  2. Click "App Passwords", just below the "2 step verification" tick.单击“两步验证”复选框下方的“应用程序密码”。
  3. Request a new password for the mail app.请求邮件应用程序的新密码。 在此处输入图像描述

Now just use this password instead of the original one for you account!现在只需使用此密码而不是您帐户的原始密码!

public static void SendMail2Step(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body, string[] FileNames) {            
            var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                EnableSsl = true
            };                
            smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
            var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
            smtpClient.Send(message);
    }

Use like this:像这样使用:

SendMail2Step("smtp.gmail.com", 587, "youraccount@gmail.com",
          "yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
          "recipient@barcodes.bg", "test message subject", "Test message body ...", null);

For the other answers to work "from a server" first Turn On Access for less secure apps in the gmail account.对于“从服务器”工作的其他答案,首先为 gmail 帐户中不太安全的应用程序打开访问权限 This will be deprecated 30 May 2022这将于 2022 年 5 月 30 日弃用

Looks like recently google changed it's security policy.看起来最近谷歌改变了它的安全政策。 The top rated answer no longer works, until you change your account settings as described here: https://support.google.com/accounts/answer/6010255?hl=en-GB As of March 2016, google changed the setting location again!评分最高的答案不再有效,除非您按照此处所述更改您的帐户设置:https: //support.google.com/accounts/answer/6010255?hl=en-GB截至 2016 年 3 月,谷歌再次更改了设置位置! 在此处输入图像描述

This is to send email with attachement.. Simple and short..这是发送带有附件的电子邮件..简单而简短..

source: http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html来源: http ://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html

using System.Net;
using System.Net.Mail;

public void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("your mail@gmail.com");
    mail.To.Add("to_mail@gmail.com");
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your mail@gmail.com", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

Google may block sign in attempts from some apps or devices that do not use modern security standards. Google 可能会阻止来自不使用现代安全标准的某些应用或设备的登录尝试。 Since these apps and devices are easier to break into, blocking them helps keep your account safer.由于这些应用程序和设备更容易被入侵,因此阻止它们有助于确保您的帐户更安全。

Some examples of apps that do not support the latest security standards include:一些不支持最新安全标准的应用示例包括:

  • The Mail app on your iPhone or iPad with iOS 6 or below装有 iOS 6 或更低版本的 iPhone 或 iPad 上的邮件应用
  • The Mail app on your Windows phone preceding the 8.1 release 8.1 版本之前的 Windows 手机上的邮件应用程序
  • Some Desktop mail clients like Microsoft Outlook and Mozilla Thunderbird一些桌面邮件客户端,如 Microsoft Outlook 和 Mozilla Thunderbird

Therefore, you have to enable Less Secure Sign-In in your google account.因此,您必须在您的 google 帐户中启用不太安全的登录

After sign into google account, go to:登录谷歌账号后,访问:

https://myaccount.google.com/lesssecureapps https://myaccount.google.com/lesssecureapps
or或者
https://www.google.com/settings/security/lesssecureapps https://www.google.com/settings/security/lesssecureapps

In C#, you can use the following code:在 C# 中,您可以使用以下代码:

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("email@gmail.com");
    mail.To.Add("somebody@domain.com");
    mail.Subject = "Hello World";
    mail.Body = "<h1>Hello</h1>";
    mail.IsBodyHtml = true;
    mail.Attachments.Add(new Attachment("C:\\file.zip"));

    using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
    {
        smtp.Credentials = new NetworkCredential("email@gmail.com", "password");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
}

For me to get it to work, i had to enable my gmail account making it possible for other apps to gain access.为了让它工作,我必须启用我的 gmail 帐户才能让其他应用程序获得访问权限。 This is done with the "enable less secure apps" and also using this link: https://accounts.google.com/b/0/DisplayUnlockCaptcha这是通过“启用不太安全的应用程序”使用此链接完成的: https ://accounts.google.com/b/0/DisplayUnlockCaptcha

Here is my version: " Send Email In C # Using Gmail ".这是我的版本:“在 C# 中使用 Gmail 发送电子邮件”。

using System;
using System.Net;
using System.Net.Mail;

namespace SendMailViaGmail
{
   class Program
   {
   static void Main(string[] args)
   {

      //Specify senders gmail address
      string SendersAddress = "Sendersaddress@gmail.com";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "ReceiversAddress@yahoo.com";
      //Specify The password of gmial account u are using to sent mail(pw of sender@gmail.com)
      const string SendersPassword = "Password";
      //Write the subject of ur mail
      const string subject = "Testing";
      //Write the contents of your mail
      const string body = "Hi This Is my Mail From Gmail";

      try
      {
        //we will use Smtp client which allows us to send email using SMTP Protocol
        //i have specified the properties of SmtpClient smtp within{}
        //gmails smtp server name is smtp.gmail.com and port number is 587
        SmtpClient smtp = new SmtpClient
        {
           Host = "smtp.gmail.com",
           Port = 587,
           EnableSsl = true,
           DeliveryMethod = SmtpDeliveryMethod.Network,
           Credentials    = new NetworkCredential(SendersAddress, SendersPassword),
           Timeout = 3000
        };

        //MailMessage represents a mail message
        //it is 4 parameters(From,TO,subject,body)

        MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
        /*WE use smtp sever we specified above to send the message(MailMessage message)*/

        smtp.Send(message);
        Console.WriteLine("Message Sent Successfully");
        Console.ReadKey();
     }

     catch (Exception ex)
     {
        Console.WriteLine(ex.Message);
        Console.ReadKey();
     }
    }
   }
 }

I hope this code will work fine.我希望这段代码能正常工作。 You can have a try.你可以试一试。

// Include this.                
using System.Net.Mail;

string fromAddress = "xyz@gmail.com";
string mailPassword = "*****";       // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";


// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);


// Fill the mail form.
var send_mail = new MailMessage();

send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("from@gmail.com");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("to@example.com");
//subject of the mail.
send_mail.Subject = "put any subject here";

send_mail.Body = messageBody;
client.Send(send_mail);

Source : Send email in ASP.NET C#来源在 ASP.NET C# 中发送电子邮件

Below is a sample working code for sending in a mail using C#, in the below example I am using google's smtp server.下面是使用 C# 发送邮件的示例工作代码,在下面的示例中,我使用的是 google 的 smtp 服务器。

The code is pretty self explanatory, replace email and password with your email and password values.该代码非常不言自明,将电子邮件和密码替换为您的电子邮件和密码值。

public void SendEmail(string address, string subject, string message)
{
    string email = "yrshaikh.mail@gmail.com";
    string password = "put-your-GMAIL-password-here";

    var loginInfo = new NetworkCredential(email, password);
    var msg = new MailMessage();
    var smtpClient = new SmtpClient("smtp.gmail.com", 587);

    msg.From = new MailAddress(email);
    msg.To.Add(new MailAddress(address));
    msg.Subject = subject;
    msg.Body = message;
    msg.IsBodyHtml = true;

    smtpClient.EnableSsl = true;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = loginInfo;
    smtpClient.Send(msg);
}

为避免 Gmail 中的安全问题,您应首先从 Gmail 设置中生成应用密码,即使您使用两步验证,您也可以使用此密码而不是真实密码发送电子邮件。

Include this,包括这个,

using System.Net.Mail;

And then,接着,

MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); 
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt16("587");
client.Credentials = new System.Net.NetworkCredential("mail-id@gmail.com","password");
client.EnableSsl = true;

client.Send(sendmsg);

If you want to send background email, then please do the below如果您想发送后台电子邮件,请执行以下操作

 public void SendEmail(string address, string subject, string message)
 {
 Thread threadSendMails;
 threadSendMails = new Thread(delegate()
    {

      //Place your Code here 

     });
  threadSendMails.IsBackground = true;
  threadSendMails.Start();
}

and add namespace并添加命名空间

using System.Threading;

Try This,尝试这个,

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("your_email_address@gmail.com");
            mail.To.Add("to_address");
            mail.Subject = "Test Mail";
            mail.Body = "This is for testing SMTP mail from GMAIL";

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            MessageBox.Show("mail Send");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

use this way用这种方式

MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); 
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt32("587");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("mail-id@gmail.com","MyPassWord");
client.Send(sendmsg);

Don't forget this :不要忘记这一点:

using System.Net;
using System.Net.Mail;

Changing sender on Gmail / Outlook.com email:在 Gmail / Outlook.com 电子邮件上更改发件人:

To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.为了防止欺骗 - Gmail/Outlook.com 不会让您从任意用户帐户名发送。

If you have a limited number of senders you can follow these instructions and then set the From field to this address: Sending mail from a different address如果您的发件人数量有限,您可以按照以下说明操作,然后将“ From ”字段设置为此地址: 从不同地址发送邮件

If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :如果您想从任意电子邮件地址发送(例如用户输入电子邮件的网站上的反馈表,并且您不希望他们直接向您发送电子邮件),那么您可以做的最好的事情是:

        msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));

This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.这将使您只需在您的电子邮件帐户中点击“回复”即可在反馈页面上回复您乐队的粉丝,但他们不会收到您的实际电子邮件,这可能会导致大量垃圾邮件。

If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).如果您处于受控环境中,这非常有用,但请注意,即使指定了回复(我不知道是哪个),我也看到一些电子邮件客户端发送到发件人地址。

using System;
using System.Net;
using System.Net.Mail;

namespace SendMailViaGmail
{
   class Program
   {
   static void Main(string[] args)
   {

      //Specify senders gmail address
      string SendersAddress = "Sendersaddress@gmail.com";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "ReceiversAddress@yahoo.com";
      //Specify The password of gmial account u are using to sent mail(pw of sender@gmail.com)
      const string SendersPassword = "Password";
      //Write the subject of ur mail
      const string subject = "Testing";
      //Write the contents of your mail
      const string body = "Hi This Is my Mail From Gmail";

      try
      {
        //we will use Smtp client which allows us to send email using SMTP Protocol
        //i have specified the properties of SmtpClient smtp within{}
        //gmails smtp server name is smtp.gmail.com and port number is 587
        SmtpClient smtp = new SmtpClient
        {
           Host = "smtp.gmail.com",
           Port = 587,
           EnableSsl = true,
           DeliveryMethod = SmtpDeliveryMethod.Network,
           Credentials = new NetworkCredential(SendersAddress, SendersPassword),
           Timeout = 3000
        };

        //MailMessage represents a mail message
        //it is 4 parameters(From,TO,subject,body)

        MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
        /*WE use smtp sever we specified above to send the message(MailMessage message)*/

        smtp.Send(message);
        Console.WriteLine("Message Sent Successfully");
        Console.ReadKey();
     }
     catch (Exception ex)
     {
        Console.WriteLine(ex.Message);
        Console.ReadKey();
     }
}
}
}

I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps .我遇到了同样的问题,但是通过转到 gmail 的安全设置和Allowing Less Secure apps解决了这个问题。 The Code from Domenic & Donny works, but only if you enabled that setting Domenic & Donny 的代码有效,但前提是您启用了该设置

If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"如果您已登录(Google),您可以点击链接并切换“开启”以获取“访问安全性较低的应用程序”

One Tip! 一个提示! Check the sender inbox, maybe you need allow less secure apps. 检查发件人收件箱,也许您需要允许不太安全的应用程序。 See: https://www.google.com/settings/security/lesssecureapps 请参阅: https//www.google.com/settings/security/lesssecureapps

From 1 Jun 2022, Google has added some security features从 2022 年 6 月 1 日起,Google 添加了一些安全功能

Google is no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password or send mail directly using username and password of google account. Google 不再支持使用第三方应用程序或设备要求您仅使用您的用户名和密码登录您的 Google 帐户或直接使用 Google 帐户的用户名和密码发送邮件。 But you still can send E-Mail via your gmail account using generating app password.但是您仍然可以使用生成应用程序密码通过您的 gmail 帐户发送电子邮件。

Below are the steps for generate new password.以下是生成新密码的步骤。

  1. Go to https://myaccount.google.com/security转到https://myaccount.google.com/security
  2. Turn on two step verification.开启两步验证。
  3. Confirm your account by phone if needed.如果需要,请通过电话确认您的帐户。
  4. Click "App Passwords", just below the "2 step verification" tick.单击“应用程序密码”,就在“两步验证”勾选下方。 Request a new password for the mail app.为邮件应用程序请求一个新密码。

Now we have to use this password for sending mail instead of the original password of your account.现在我们必须使用这个密码来发送邮件,而不是您帐户的原始密码。

Below is the example code for sending mail下面是发送邮件的示例代码

public static void SendMailFromApp(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body) {            
            var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                EnableSsl = true
            };                
            smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
            var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
            smtpClient.Send(message);
    }

You can to call method like below您可以像下面这样调用方法

SendMailFromApp("smtp.gmail.com", 25, "mygmailaccount@gmail.com",
          "tyugyyj1556jhghg",//This will be generated by google, copy it here.
          "mailme@gmail.com", "New Mail Subject", "Body of mail from My App");

Here is one method to send mail and getting credentials from web.config:这是从 web.config 发送邮件和获取凭据的一种方法:

public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
    try
    {
        System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
        newMsg.BodyEncoding = System.Text.Encoding.UTF8;
        newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
        newMsg.SubjectEncoding = System.Text.Encoding.UTF8;

        System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
        if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
        {
            System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
            System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
            disposition.FileName = AttachmentFileName;
            disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;

            newMsg.Attachments.Add(attachment);
        }
        if (test)
        {
            smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
            smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
        }
        else
        {
            //smtpClient.EnableSsl = true;
        }

        newMsg.IsBodyHtml = bodyHtml;
        smtpClient.Send(newMsg);
        return SENT_OK;
    }
    catch (Exception ex)
    {

        return "Error: " + ex.Message
             + "<br/><br/>Inner Exception: "
             + ex.InnerException;
    }

}

And the corresponding section in web.config:以及 web.config 中的相应部分:

<appSettings>
    <add key="mailCfg" value="yourmail@example.com"/>
</appSettings>
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="yourmail@example.com">
      <network defaultCredentials="false" host="mail.exapmple.com" userName="yourmail@example.com" password="your_password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>

Try this one试试这个

public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
        MailMessage mailMessage = new MailMessage();
        MailAddress mailAddress = new MailAddress("abc@gmail.com", "Sender Name"); // abc@gmail.com = input Sender Email Address 
        mailMessage.From = mailAddress;
        mailAddress = new MailAddress(receiverEmail, ReceiverName);
        mailMessage.To.Add(mailAddress);
        mailMessage.Subject = subject;
        mailMessage.Body = body;
        mailMessage.IsBodyHtml = true;

        SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587)
        {
            EnableSsl = true,
            UseDefaultCredentials = false,
            DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
            Credentials = new NetworkCredential("abc@gmail.com", "pass")   // abc@gmail.com = input sender email address  
                                                                           //pass = sender email password
        };

        try
        {
            mailSender.Send(mailMessage);
            return true;
        }
        catch (SmtpFailedRecipientException ex)
        { 
          // Write the exception to a Log file.
        }
        catch (SmtpException ex)
        { 
           // Write the exception to a Log file.
        }
        finally
        {
            mailSender = null;
            mailMessage.Dispose();
        }
        return false;
}

对我来说,问题是我的密码中包含一个黑杠“ \\” ,我在粘贴粘贴时没有意识到会引起问题。

Copying from another answer , the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account.另一个答案复制,上述方法有效,但 gmail 总是用实际发送 gmail 帐户替换“发件人”和“回复”电子邮件。 apparently there is a work around however:显然有一个解决方法:

http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html

"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it" “3. 在“帐户”选项卡中,单击“添加您拥有的另一个电子邮件地址”链接,然后进行验证”

Or possibly this或者可能这个

Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."更新 3:读者 Derek Bennett 说,“解决方案是进入您的 gmail 设置:帐户并“设为默认”一个帐户,而不是您的 gmail 帐户。这将导致 gmail 使用默认帐户的电子邮件重新写入“发件人”字段地址是。”

You can try Mailkit .你可以试试Mailkit It gives you better and advance functionality for send mail.它为您提供了更好、更先进的发送邮件功能。 You can find more from this Here is an example你可以从这里找到更多是一个例子

    MimeMessage message = new MimeMessage();
    message.From.Add(new MailboxAddress("FromName", "YOU_FROM_ADDRESS@gmail.com"));
    message.To.Add(new MailboxAddress("ToName", "YOU_TO_ADDRESS@gmail.com"));
    message.Subject = "MyEmailSubject";

    message.Body = new TextPart("plain")
    {
        Text = @"MyEmailBodyOnlyTextPart"
    };

    using (var client = new SmtpClient())
    {
        client.Connect("SERVER", 25); // 25 is port you can change accordingly

        // Note: since we don't have an OAuth2 token, disable
        // the XOAUTH2 authentication mechanism.
        client.AuthenticationMechanisms.Remove("XOAUTH2");

        // Note: only needed if the SMTP server requires authentication
        client.Authenticate("YOUR_USER_NAME", "YOUR_PASSWORD");

        client.Send(message);
        client.Disconnect(true);
    }

在此处输入图像描述

Google has removed the less secure apps setting from our Google accounts, this means that we can no longer send emails from the SMTP server using our actual google passwords.谷歌已经从我们的谷歌账户中删除了安全性较低的应用程序设置,这意味着我们不能再使用我们实际的谷歌密码从 SMTP 服务器发送电子邮件。 We need to either use Xoauth2 and authorize the user or create a an apps password on an account that has 2fa enabled.我们需要使用 Xoauth2 并授权用户或在启用了 2fa 的帐户上创建应用密码。

Once created an apps password can be used in place of your standard gmail password.一旦创建了一个应用程序密码,就可以用来代替你的标准 gmail 密码。

class Program
{
    private const string To = "test@test.com";
    private const string From = "test@test.com";
    
    private const string GoogleAppPassword = "XXXXXXXX";
    
    private const string Subject = "Test email";
    private const string Body = "<h1>Hello</h1>";
    
    
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        
        var smtpClient = new SmtpClient("smtp.gmail.com")
        {
            Port = 587,
            Credentials = new NetworkCredential(From , GoogleAppPassword),
            EnableSsl = true,
        };
        var mailMessage = new MailMessage
        {
            From = new MailAddress(From),
            Subject = Subject,
            Body = Body,
            IsBodyHtml = true,
        };
        mailMessage.To.Add(To);

        smtpClient.Send(mailMessage);
    }
}

Quick fix for SMTP username and password not accepted error快速修复 SMTP 用户名和密码未被接受的错误

After google update, This is the valid method to send an email using c# or .net.谷歌更新后,这是使用 c# 或 .net 发送电子邮件的有效方法。

using System;
using System.Net;
using System.Net.Mail;

namespace EmailApp
{
    internal class Program
    {
        public static void Main(string[] args)
        {
            String SendMailFrom = "Sender Email";
            String SendMailTo = "Reciever Email";
            String SendMailSubject = "Email Subject";
            String SendMailBody = "Email Body";

            try
            {
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587);
                SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
                MailMessage email = new MailMessage();
                // START
                email.From = new MailAddress(SendMailFrom);
                email.To.Add(SendMailTo);
                email.CC.Add(SendMailFrom);
                email.Subject = SendMailSubject;
                email.Body = SendMailBody;
                //END
                SmtpServer.Timeout = 5000;
                SmtpServer.EnableSsl = true;
                SmtpServer.UseDefaultCredentials = false;
                SmtpServer.Credentials = new NetworkCredential(SendMailFrom, "Google App Password");
                SmtpServer.Send(email);

                Console.WriteLine("Email Successfully Sent");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }

        }
    }
}

For creating the app password, you can follow this article: https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html创建应用密码,您可以参考这篇文章: https ://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html

如何为 gmail 设置应用程序专用密码

If your Google password doesn't work, you may need to create an app-specific password for Gmail on Google.如果您的 Google 密码无效,您可能需要为 Google 上的 Gmail 创建一个应用专用密码。 https://support.google.com/accounts/answer/185833?hl=en https://support.google.com/accounts/answer/185833?hl=en

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM