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

Sending email in .NET through Gmail

提问人:Mike Wills 提问时间:8/28/2008 最后编辑:Arsen KhachaturyanMike Wills 更新时间:12/18/2022 访问量:658935

问:

我没有依靠我的主机发送电子邮件,而是考虑使用我的Gmail帐户发送电子邮件。这些电子邮件是发给我在节目中演奏的乐队的个性化电子邮件。

有可能做到吗?

C# .NET 电子邮件 SMTP Gmail

评论

13赞 noocyte 10/5/2011
如果您使用的是 ASP.Net Mvc,我建议您查看 MvcMailer:github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
0赞 Simon_Weaver 7/8/2013
请注意发件人限制(我希望您的乐队足够成功,这是一个问题)support.google.com/a/bin/answer.py?hl=en&answer=166852
0赞 Joel Santos 10/8/2013
简单的方法在这里阅读它。stackoverflow.com/questions/9201239/......
0赞 Gustavo Rossi Muller 7/22/2015
一个提示!检查发件人收件箱,也许您需要允许安全性较低的应用程序。请参见:google.com/settings/security/lesssecureapps
0赞 Satbir Kira 6/15/2015
对我来说,问题是我的密码中有一个黑斜杠“\\”,我复制粘贴时没有意识到这会导致问题。

答:

1165赞 Domenic 8/28/2008 #1

请务必使用 ,而不是已弃用的 .使用SSL是一堆乱七八糟的黑客扩展。System.Net.MailSystem.Web.MailSystem.Web.Mail

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

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "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);
}

此外,请转到 Google 帐号>安全页面,然后查看登录 Google >两步验证设置。

  • 如果启用,则必须生成一个密码,允许 .NET 绕过两步验证。为此,请单击“登录 Google”>“应用密码”,选择“应用 = 邮件”和“设备 = Windows 计算机”,最后生成密码。在常量中使用生成的密码,而不是标准的 Gmail 密码。fromPassword
  • 如果它被禁用,那么你必须打开不太安全的应用程序访问,这是不建议的!因此,最好启用两步验证。

评论

54赞 Jason Short 8/26/2009
如果 Google 突然决定您在过去 xx 分钟内发送了太多内容,您仍然可以收到用户未登录错误。您应该始终添加一个 trySend,如果它错误睡眠一段时间,然后重试。
76赞 Nathan Wheeler 11/18/2009
有趣的说明:如果交换“UseDefaultCredentials = false”和“Credentials = ...”它不会进行身份验证。
13赞 Meinersbur 3/19/2010
使用此方法的 SPF 没有问题。每个电子邮件客户端都可以配置为完全做到这一点。如果您使用自己的服务器(即其他服务器)作为发件人,您可能会遇到问题。顺便说一句:如果发件人地址不是您的,则会自动覆盖该地址。smtp.gmail.com[email protected]smtp.gmail.com
25赞 yourbuddypal 8/6/2012
即使尝试了各种调整,我也很难让它工作。正如相关帖子中所建议的那样,我发现实际上是我的防病毒软件阻止了电子邮件成功发送。有问题的防病毒软件是McAffee,其“访问保护”具有“防病毒标准保护”类别,该类别具有“防止群发邮件蠕虫发送电子邮件”规则。调整/禁用该规则使此代码为我工作!
20赞 Nick DeVore 6/18/2013
我收到 5.5.1 Authentication Required 错误消息,直到我意识到我正在使用一个启用了双因素身份验证的帐户(我的个人帐户)进行测试。一旦我使用了一个没有它的帐户,它就可以正常工作。我还可以为我的应用程序生成一个密码,我正在我的个人帐户中进行测试,但我不想这样做。
166赞 Donny V. 1/29/2009 #2

上面的答案是行不通的。您必须设置,否则它将返回“客户端未通过身份验证”错误。此外,设置超时总是一个好主意。DeliveryMethod = SmtpDeliveryMethod.Network

修改后的代码:

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

var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "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);
}

评论

3赞 Domenic 3/17/2009
嗯,我的猜测是 SmtpDeliveryMethod.Network 是默认值,但在 IIS 中运行时可能会更改默认值---那是您正在做的事情吗?
3赞 Karthikeyan P 8/26/2015
我在控制台应用程序中使用相同的代码,这是通过错误“发送邮件失败”。
6赞 1/19/2016
这个答案是行不通的。请看这个问题 stackoverflow.com/questions/34851484/......
18赞 tehie 10/18/2010 #3

这是我的版本:“使用 Gmail 在 C # 中发送电子邮件”。

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

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

      //Specify senders gmail address
      string SendersAddress = "[email protected]";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "[email protected]";
      //Specify The password of gmial account u are using to sent mail(pw of [email protected])
      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();
     }
    }
   }
 }

评论

8赞 sarnold 1/16/2012
虽然您的文章实际上可能回答了这个问题,但最好在此处包含答案的基本部分,并提供链接以供参考。Stack Overflow 的用处取决于它的问题和答案,如果您的博客主机出现故障或您的 URL 被移动,则此答案将变得毫无用处。谢谢!
46赞 Ranadheer Reddy 5/28/2012 #4

这是发送带有附件的电子邮件。简单而简短..

来源: 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 [email protected]");
    mail.To.Add("[email protected]");
    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 [email protected]", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}
12赞 Yasser Shaikh 8/22/2012 #5

来源在 ASP.NET C# 中发送电子邮件

下面是一个使用 C# 发送邮件的示例工作代码,在下面的示例中,我使用的是 google 的 smtp 服务器。

该代码不言自明,将电子邮件和密码替换为您的电子邮件和密码值。

public void SendEmail(string address, string subject, string message)
{
    string email = "[email protected]";
    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);
}

评论

0赞 Jui Test 2/28/2013
我使用了 NetworkCredential、MailMessage 等类名,而不是 var,SmtpClient.It 对我有用。
1赞 Soliman Soliman 9/15/2020
这对我有用。除了上面提到的所有有效和优点之外,例如上面提到的 gmail 安全内容。它起作用的原因是需要首先关闭对象的默认凭据,这些凭据可能是空的或留空的,然后才能设置其 SmtpClient 凭据,而不是 AFTER。谢谢亚西尔·谢赫。
5赞 Simon_Weaver 7/8/2013 #6

更改 Gmail / Outlook.com 电子邮件的发件人:

为了防止欺骗 - Gmail/Outlook.com 不允许您从任意用户帐户名称发送邮件。

如果发件人数量有限,可以按照以下说明操作,然后将字段设置为以下地址: 从其他地址发送邮件From

如果您想从任意电子邮件地址发送(例如用户输入电子邮件的网站上的反馈表,而您不希望他们直接向您发送电子邮件),那么您能做的最好的事情就是:

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

这样一来,您只需在电子邮件帐户中点击“回复”即可在反馈页面上回复乐队的粉丝,但他们不会收到您的实际电子邮件,这可能会导致大量垃圾邮件。

如果您在受控环境中,这很好用,但请注意,即使指定了回复,我也看到一些电子邮件客户端发送到发件人地址(我不知道是哪个)。

9赞 RAJESH KUMAR 7/23/2013 #7

如果要发送后台电子邮件,请执行以下操作

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

      //Place your Code here 

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

并添加命名空间

using System.Threading;
2赞 iTURTEV 10/8/2013 #8

下面是发送邮件并从 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;
    }

}

以及 web.config 中的相应部分:

<appSettings>
    <add key="mailCfg" value="[email protected]"/>
</appSettings>
<system.net>
  <mailSettings>
    <smtp deliveryMethod="Network" from="[email protected]">
      <network defaultCredentials="false" host="mail.exapmple.com" userName="[email protected]" password="your_password" port="25"/>
    </smtp>
  </mailSettings>
</system.net>
11赞 GOPI 10/9/2013 #9

包括这个,

using System.Net.Mail;

然后

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

client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");
client.EnableSsl = true;

client.Send(sendmsg);
16赞 Premdeep Mohanty 10/15/2013 #10

我希望这段代码能正常工作。你可以试一试。

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

string fromAddress = "[email protected]";
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("[email protected]");
//address to which mail will be sent.           
send_mail.To.Add(new MailAddress("[email protected]");
//subject of the mail.
send_mail.Subject = "put any subject here";

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

评论

2赞 Debaprasad 3/18/2014
消息 send_mail = new MailMessage();这条线应该如何工作?不能将“System.Net.Mail.MailMessage”隐式转换为“System.Windows.Forms.Message”
24赞 Mark Homans 1/3/2014 #11

为了让它正常工作,我必须启用我的 gmail 帐户,以便其他应用程序能够访问。这是通过“启用安全性较低的应用程序”完成的,也可以使用此链接:https://accounts.google.com/b/0/DisplayUnlockCaptcha

25赞 mjb 8/9/2014 #12

Google 可能会阻止某些未使用现代安全标准的应用或设备尝试登录。由于这些应用和设备更容易被入侵,因此阻止它们有助于提高帐户的安全性。

不支持最新安全标准的应用示例包括:

  • 装有 iOS 6 或更低版本的 iPhone 或 iPad 上的“邮件”应用
  • 8.1 版本之前的 Windows Phone 上的“邮件”应用
  • 一些桌面邮件客户端,如Microsoft Outlook和Mozilla Thunderbird

因此,您必须在Google帐户中启用不太安全的登录

登录Google帐户后,转到:

https://myaccount.google.com/lesssecureapps

https://www.google.com/settings/security/lesssecureapps

在 C# 中,可以使用以下代码:

using (MailMessage mail = new MailMessage())
{
    mail.From = new MailAddress("[email protected]");
    mail.To.Add("[email protected]");
    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 protected]", "password");
        smtp.EnableSsl = true;
        smtp.Send(mail);
    }
}
5赞 DarkPh03n1X 6/25/2015 #13

我遇到了同样的问题,但通过转到 gmail 的安全设置和允许不太安全的应用程序解决了这个问题。 Domenic & Donny 的代码有效,但前提是您启用了该设置

如果您已登录(Google),则可以点击链接,然后将“打开”切换为“访问安全性较低的应用程序”

6赞 alireza amini 7/9/2015 #14

以这种方式使用

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("[email protected]","MyPassWord");
client.Send(sendmsg);

别忘了这一点:

using System.Net;
using System.Net.Mail;
159赞 BCS Software 9/8/2015 #15

编辑 2022自 2022 年 5 月 30 日起,Google 将不再支持使用仅要求您使用用户名和密码登录 Google 帐号的第三方应用或设备。但是您仍然可以通过您的Gmail帐户发送电子邮件。

  1. 转到 https://myaccount.google.com/security 并开启两步验证。如果需要,请通过电话确认您的帐户。
  2. 点击“应用密码”,就在“两步验证”勾选下方。
  3. 为邮件应用程序请求新密码。enter image description here

现在只需使用此密码而不是您帐户的原始密码!

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

像这样使用:

SendMail2Step("smtp.gmail.com", 587, "[email protected]",
          "yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
          "[email protected]", "test message subject", "Test message body ...", null);

要使其他答案“从服务器”工作,请先为 gmail 帐户中安全性较低的应用打开访问权限这将在 2022 年 5 月 30 日弃用

看起来最近谷歌改变了它的安全策略。评分最高的答案不再有效,直到您按照以下说明更改帐户设置: https://support.google.com/accounts/answer/6010255?hl=en-GB 截至 2016 年 3 月,谷歌再次更改了设置位置! enter image description here

评论

4赞 Sully 4/13/2016
这对我有用。而且也令人担忧。不确定我是否要关闭该安全性。可能需要重新考虑......
6赞 Michael Freidgeim 6/5/2016
从安全角度来看,最好打开两步验证,然后生成和使用应用密码 - 请参阅如何根据新的安全策略在 .Net 中发送电子邮件?
2赞 Alaa' 1/18/2018
@BCS软件,在我的程序中,用户插入任何电子邮件,我的程序必须使用它来发送消息。那么,即使打开了 2 因素身份验证,我如何使电子邮件用户能够发送电子邮件?
0赞 Brett Rigby 4/23/2019
如果您想使用 Microsoft Outlook 客户端(在台式机、移动电话等上)通过 Google 的 GMail 发送/接收电子邮件,则需要更改此设置。
0赞 Andrei Bazanov 10/6/2020
这对我来说很有帮助。但请确保尽快将其放回原处:)
5赞 Moin Shirazi 10/10/2015 #16
using System;
using System.Net;
using System.Net.Mail;

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

      //Specify senders gmail address
      string SendersAddress = "[email protected]";
      //Specify The Address You want to sent Email To(can be any valid email address)
      string ReceiversAddress = "[email protected]";
      //Specify The password of gmial account u are using to sent mail(pw of [email protected])
      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();
     }
}
}
}
2赞 reza.cse08 2/27/2016 #17

试试这个

public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
        MailMessage mailMessage = new MailMessage();
        MailAddress mailAddress = new MailAddress("[email protected]", "Sender Name"); // [email protected] = 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("[email protected]", "pass")   // [email protected] = 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;
}
7赞 Trimantra Software Solution 1/31/2017 #18

试试这个,

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

            mail.From = new MailAddress("[email protected]");
            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());
        }
    }
1赞 rogerdpack 3/22/2018 #19

另一个答案复制,上述方法有效,但 gmail 始终将“发件人”和“回复”电子邮件替换为实际发送的 gmail 帐户。然而,显然有一个解决方法:

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

“3. 在”帐户“选项卡中,单击”添加您拥有的另一个电子邮件地址“链接,然后进行验证”

或者可能是这个

更新3:读者德里克·贝内特(Derek Bennett)说:“解决方案是进入您的gmail设置:帐户并”默认“您的gmail帐户以外的帐户。这将导致 gmail 使用默认帐户的电子邮件地址重写“发件人”字段。

2赞 Naveen 6/3/2019 #20

你可以试试。它为您提供了更好和先进的发送邮件功能。你可以从中找到更多信息 这是一个例子Mailkit

    MimeMessage message = new MimeMessage();
    message.From.Add(new MailboxAddress("FromName", "[email protected]"));
    message.To.Add(new MailboxAddress("ToName", "[email protected]"));
    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);
    }
12赞 Sayed Uz Zaman 7/17/2019 #21

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

评论

0赞 Cees 1/26/2022
是的,我同意对于 gmail,您需要进行设置。但是,我不太热衷于使用第二个安全性较低的密码来完全访问我的帐户。如果您可以以某种方式集成“使用 google 登录”并将令牌存储在应用程序上,这可能是一个更好的解决方案。但是,我还没有对此进行测试。
1赞 Hasala Senevirathne 9/8/2020 #22

How to Set App-specific password for gmail

如果您的 Google 密码不起作用,您可能需要为 Google 上的 Gmail 创建应用专用密码。https://support.google.com/accounts/answer/185833?hl=en

评论

1赞 Leandro Bardelli 6/17/2021
这是一个评论。
2赞 Sunny Okoro Awa 8/14/2022 #23

如果您现在尝试执行此操作,则不再支持此功能。

https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637960864118404117-800836189&p=less-secure-apps&rd=1#zippy=

enter image description here

7赞 Bhadresh Patel 10/13/2022 #24

从 2022 年 6 月 1 日起,Google 增加了一些安全功能

Google 不再支持使用第三方应用或设备,这些应用或设备要求您仅使用您的用户名和密码登录您的 Google 帐户,或直接使用 Google 帐户的用户名和密码发送邮件。但是您仍然可以使用生成应用程序密码通过您的Gmail帐户发送电子邮件。

以下是生成新密码的步骤。

  1. 转到 https://myaccount.google.com/security
  2. 开启两步验证。
  3. 如果需要,请通过电话确认您的帐户。
  4. 点击“应用密码”,就在“两步验证”勾选下方。为邮件应用程序请求新密码。

现在,我们必须使用此密码来发送邮件,而不是您帐户的原始密码。

以下是发送邮件的示例代码

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

您可以调用如下方法

SendMailFromApp("smtp.gmail.com", 25, "[email protected]",
          "tyugyyj1556jhghg",//This will be generated by google, copy it here.
          "[email protected]", "New Mail Subject", "Body of mail from My App");
3赞 Linda Lawton - DaImTo 11/11/2022 #25

enter image description here

Google 已从我们的 Google 帐户中删除了安全性较低的应用程序设置,这意味着我们无法再使用实际的 Google 密码从 SMTP 服务器发送电子邮件。我们需要使用 Xoauth2 并授权用户,或者在启用了 2fa 的帐户上创建应用密码。

创建后,可以使用应用密码代替标准 gmail 密码。

class Program
{
    private const string To = "[email protected]";
    private const string From = "[email protected]";
    
    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);
    }
}

SMTP用户名和密码未接受错误的快速修复

3赞 Ahsan Ehtesham 12/18/2022 #26

谷歌更新后,这是使用 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();
            }

        }
    }
}

若要创建应用密码,可以按照以下文章操作:https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html