我想用我的Gmail帐户发送电子邮件,而不是依靠我的主机发送电子邮件。这些邮件是发给我在节目中演出的乐队的个性化邮件。

有可能做到吗?


一定要使用System.Net。邮件,而不是已弃用的System.Web.Mail。使用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);
}

此外,转到谷歌帐户>安全页面,并查看登录谷歌> 2步验证设置。

如果启用了,那么您必须生成一个密码,允许. net绕过2步验证。点击“Signing in To谷歌> App passwords”,选择App = Mail, device = Windows Computer,最后生成密码。在fromPassword常量中使用生成的密码,而不是标准的Gmail密码。 如果它被禁用,那么你必须打开Less secure app access,这是不推荐的!所以最好启用两步验证。


上面的答案不管用。必须设置DeliveryMethod = SmtpDeliveryMethod。网络,否则将返回“客户端未经过身份验证”错误。此外,暂停总是一个好主意。

修改后的代码:

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

这是我的版本:“发送电子邮件在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();
     }
    }
   }
 }

这是发送邮件的附件。简单而简短。

来源: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);

}

来源:在ASP发送电子邮件。净c#

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

代码是相当不言自明的,替换电子邮件和密码与您的电子邮件和密码值。

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 / Outlook.com邮箱更改发件人:

为了防止欺骗- Gmail/Outlook.com不会让你从任意用户帐户名发送。

如果发件人数量有限,则可以按照以下说明将From字段设置为此地址:从不同地址发送邮件

如果你想从一个任意的电子邮件地址发送(比如用户在网站上输入他们的电子邮件,而你不希望他们直接给你发送电子邮件),你能做的最好的是:

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

这可以让你在电子邮件账户中点击“回复”,在反馈页面上回复你乐队的粉丝,但他们不会收到你的实际电子邮件,这可能会导致大量垃圾邮件。

如果你在一个受控制的环境中,这工作得很好,但请注意,我看到一些电子邮件客户端发送到from地址,即使回复指定(我不知道是哪个)。


如果您想发送后台邮件,请执行以下操作

 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;

下面是一个从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="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>

包括这个,

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("mail-id@gmail.com","password");
client.EnableSsl = true;

client.Send(sendmsg);

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

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

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


谷歌可能会阻止一些不使用现代安全标准的应用程序或设备的登录尝试。由于这些应用程序和设备更容易被侵入,屏蔽它们有助于让你的账户更安全。

不支持最新安全标准的应用程序包括:

iOS 6或以下版本的iPhone或iPad上的邮件应用程序 8.1版本之前Windows手机上的邮件应用程序 一些桌面邮件客户端,如Microsoft Outlook和Mozilla Thunderbird

因此,您必须在您的谷歌帐户中启用“较少安全登录”。

登录谷歌账号后,进入:

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

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

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

如果您已登录(到谷歌),您可以按照此链接并切换“打开”以“访问不太安全的应用程序”


使用这种方式

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

别忘了这一点:

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

编辑2022 从2022年5月30日起,谷歌将不再支持仅使用用户名和密码登录谷歌账户的第三方应用程序或设备。 但是你仍然可以通过你的gmail账户发送电子邮件。

访问https://myaccount.google.com/security,打开两步验证。如有需要,请电话确认。 点击“应用程序密码”,就在“2步验证”勾的下方。 请求邮件应用程序的新密码。

现在只需使用这个密码,而不是原来的一个为您的帐户!

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, "youraccount@gmail.com",
          "yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
          "recipient@barcodes.bg", "test message subject", "Test message body ...", null);

对于其他答案工作“从服务器”首先打开访问gmail帐户不太安全的应用程序。这将在2022年5月30日被弃用

看来最近谷歌改变了安全策略。评分最高的答案不再有效,直到您更改您的帐户设置如下所述:https://support.google.com/accounts/answer/6010255?hl=en-GB 2016年3月,谷歌再次更改设置地点!


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

试试这个

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

试试这个,

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

从另一个答案复制,上述方法工作,但gmail总是替换“从”和“回复”电子邮件与实际发送gmail帐户。然而,显然有一种方法:

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

“3。在帐户选项卡,点击链接“添加另一个电子邮件地址你自己的”,然后验证它

或者可能是这个

更新3:读者德里克·贝内特说:“解决办法是进入你的gmail设置:账户,并“默认”一个gmail账户以外的账户。这将导致gmail用默认帐户的电子邮件地址重写From字段。”


你可以试试Mailkit。它为发送邮件提供了更好、更先进的功能。这里有一个例子

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

为了避免Gmail的安全问题,你应该先从Gmail的设置中生成一个应用程序密码,即使你使用两步验证,你也可以使用这个密码而不是真实密码来发送电子邮件。


如果你的谷歌密码不起作用,你可能需要在谷歌上为Gmail创建一个特定于应用程序的密码。 https://support.google.com/accounts/answer/185833?hl=en


这是不再支持,如果你正在尝试这样做现在。

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


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

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

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

访问https://myaccount.google.com/security 打开两步验证。 如有需要,请电话确认。 点击“应用程序密码”,就在“2步验证”勾的下方。请求邮件应用程序的新密码。

现在我们要用这个密码来发邮件,而不是你原来的账号密码。

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

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

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

一旦创建了应用程序密码,就可以用来代替你的标准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);
    }
}

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


在谷歌更新后,这是使用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