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

有可能做到吗?


当前回答

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

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

其他回答

编辑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月,谷歌再次更改设置地点!

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

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

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

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

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

 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;

一定要使用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,这是不推荐的!所以最好启用两步验证。