【问题标题】:Send email using System.Net.Mail through gmail通过 gmail 使用 System.Net.Mail 发送电子邮件
【发布时间】:2011-06-08 07:33:44
【问题描述】:

我想通过 gmail 服务器发送电子邮件。我已经输入了以下代码,但它在发送时卡住了。有什么想法请...

MailMessage mail = new MailMessage();

mail.From = new System.Net.Mail.MailAddress("apps@xxxx.com");

//create instance of smtpclient
SmtpClient smtp = new SmtpClient();
smtp.Port = 465;
smtp.UseDefaultCredentials = true;

smtp.Host = "smtp.gmail.com";            

smtp.EnableSsl = true;

//recipient address
mail.To.Add(new MailAddress("yyyy@xxxx.com"));

//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";

mail.Body = st;
smtp.Send(mail);

xxxx.com 是 Google 应用程序中的邮件域。 谢谢...

【问题讨论】:

  • 您不需要在某个地方为 SMTP 服务器输入密码吗?
  • 是的,Gmail 的 SMTP 服务器需要身份验证。 Link
  • 兰伯特所说的。默认凭据与 Windows 相关。您需要为 GMail 指定它们。

标签: c# .net email


【解决方案1】:
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("apps@xxxx.com");

// The important part -- configuring the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Port = 587;   // [1] You can try with 465 also, I always used 587 and got success
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this
smtp.UseDefaultCredentials = false; // [3] Changed this
smtp.Credentials = new NetworkCredential(mail.From,  "password_here");  // [4] Added this. Note, first parameter is NOT string.
smtp.Host = "smtp.gmail.com";            

//recipient address
mail.To.Add(new MailAddress("yyyy@xxxx.com"));

//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";

mail.Body = st;
smtp.Send(mail);

【讨论】:

  • 感谢 Sarwar... 您对端口的猜测是正确的。我明天会投票赞成。
  • 一些观察: 1. 它是“smtp.gmail.com”,而不是“smtp.google.com”。我盯着我的代码看了半个小时,直到我意识到我使用的是后者。 2. 端口 587 似乎比 465 好很多,尽管我读过的关于这个主题的所有其他内容都说使用端口 465。 3. 如果你使用两步验证,你最好是(见@ 987654321@) 您必须为您的应用程序生成一个新密码。
  • 仅供参考,当我遇到这个问题时:将您的 SmtpClient 对象包含在 using 子句中。您必须这样做,特别是如果您要在循环中使用客户端。
  • 明智的做法是使用 using 子句,以便 smtpclient “发送 QUIT 消息,然后优雅地结束 TCP 连接”。
  • 此解决方案(使用 System.Net.Mail)不适用于隐式 SSL(使用端口 465)。您必须使用其他类似 AbrahamJP 的解决方案。 (blogs.msdn.com/b/webdav_101/archive/2008/06/02/…)
【解决方案2】:

我尝试使用上述 C# 代码将邮件从 Gmail 发送到我的公司 ID。在执行应用程序时,控件无限期地停止在语句smtp.Send(mail);

在谷歌搜索时,我遇到了一个类似的code,它对我有用。我在此处发布该代码。

class GMail
{
    public void SendMail()
    {  
        string pGmailEmail = "fromAddress@gmail.com";
        string pGmailPassword = "GmailPassword";
        string pTo = "ToAddress"; //abc@domain.com
        string pSubject = "Test From Gmail";
        string pBody = "Body"; //Body
        MailFormat pFormat = MailFormat.Text; //Text Message
        string pAttachmentPath = string.Empty; //No Attachments

        System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpserver",
                          "smtp.gmail.com");
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
                          "465");
        myMail.Fields.Add
            ("http://schemas.microsoft.com/cdo/configuration/sendusing",
                          "2");
        //sendusing: cdoSendUsingPort, value 2, for sending the message using 
        //the network.

        //smtpauthenticate: Specifies the mechanism used when authenticating 
        //to an SMTP 
        //service over the network. Possible values are:
        //- cdoAnonymous, value 0. Do not authenticate.
        //- cdoBasic, value 1. Use basic clear-text authentication. 
        //When using this option you have to provide the user name and password 
        //through the sendusername and sendpassword fields.
        //- cdoNTLM, value 2. The current process security context is used to 
        // authenticate with the service.
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
        //Use 0 for anonymous
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/sendusername",
            pGmailEmail);
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/sendpassword",
             pGmailPassword);
        myMail.Fields.Add
        ("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
             "true");
        myMail.From = pGmailEmail;
        myMail.To = pTo;
        myMail.Subject = pSubject;
        myMail.BodyFormat = pFormat;
        myMail.Body = pBody;
        if (pAttachmentPath.Trim() != "")
        {
            MailAttachment MyAttachment =
                    new MailAttachment(pAttachmentPath);
            myMail.Attachments.Add(MyAttachment);
            myMail.Priority = System.Web.Mail.MailPriority.High;
        }

        SmtpMail.SmtpServer = "smtp.gmail.com:465";
        SmtpMail.Send(myMail);
    }
}

【讨论】:

  • 必须填写字段?
  • 我收到来自编译器的消息,指出 System.Web.Mail 方法已被弃用。
【解决方案3】:

设置

smtp.UseDefaultCredentials = false 

并使用

smtp.Credentials = new NetworkCredential(gMailAccount, password);

【讨论】:

  • 我也使用了这个答案。但 Sarwar 的回答完全解决了我的问题。非常感谢,我明天会对此表示赞同。干杯。
【解决方案4】:

这对我有用:

        MailMessage message = new MailMessage("myemail@gmail.com", toemail, subjectEmail, comments);
        message.IsBodyHtml = true;

        try {
            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
            client.Timeout = 2000;
            client.EnableSsl = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            //client.Credentials = CredentialCache.DefaultNetworkCredentials;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential("myemail@gmail.com", "mypassord");
            client.Send(message);

            message.Dispose();
            client.Dispose();
        }
        catch (Exception ex) {
            Debug.WriteLine(ex.Message);
        }

但是(截至撰写本文时 - 2017 年 10 月)

您需要在“我的帐户”谷歌安全/隐私设置 (https://myaccount.google.com) 的“具有帐户访问权限的应用”选项中启用“允许安全性较低的应用”

【讨论】:

    【解决方案5】:

    我意识到这是一个非常古老的问题的答案,还有很多其他好的答案。我发布此代码以包含其他用户发布的一些有用的 cmets,例如 Using Statements 和一些答案已经过时的新方法。自 2018 年 7 月 11 日起,此代码已经过测试并可以正常运行。

    如果通过您的 GMail 帐户发送,请确保从您的 control panel 启用 Allow less secure apps

    类代码 C#:

    public class Email
    {
    public void NewHeadlessEmail(string fromEmail, string password, string toAddress, string subject, string body)
    {
        using (System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage())
        {
            myMail.From = new MailAddress(fromEmail);
            myMail.To.Add(toAddress);
            myMail.Subject = subject;
            myMail.IsBodyHtml = true;
            myMail.Body = body;
    
            using (System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587))
            {
                s.DeliveryMethod = SmtpDeliveryMethod.Network;
                s.UseDefaultCredentials = false;
                s.Credentials = new System.Net.NetworkCredential(myMail.From.ToString(), password);
                s.EnableSsl = true;
                s.Send(myMail);
            }
        }
    }
    }
    

    类代码 VB:

    Public Class Email    
    Sub NewHeadlessEmail(fromEmail As String, password As String, toAddress As String, subject As String, body As String)
            Using myMail As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
                myMail.From = New MailAddress(fromEmail)
                myMail.To.Add(toAddress)
                myMail.Subject = subject
                myMail.IsBodyHtml = True
                myMail.Body = body
    
                Using s As New Net.Mail.SmtpClient("smtp.gmail.com", 587)
                    s.DeliveryMethod = SmtpDeliveryMethod.Network
                    s.UseDefaultCredentials = False
                    s.Credentials = New Net.NetworkCredential(myMail.From.ToString(), password)
                    s.EnableSsl = True
                    s.Send(myMail)
                End Using
    
            End Using
        End Sub
    End Class
    

    使用 C#:

    {
    Email em = new Email();
    em.NewHeadlessEmail("myemail@gmail.com", "password", "recipient@email.com", "Subject Text", "Body Text");
    }
    

    使用 VB:

    Dim em As New Email
    em.NewHeadlessEmail("myemail@gmail.com", "password", "recipient@email.com", "Subject Text", "Body Text")
    

    【讨论】:

      【解决方案6】:

      使用端口号 587

      使用下面的代码,就可以成功了。

      MailMessage mail = new MailMessage();
      mail.From = new MailAddress("abc@mydomain.com", "Enquiry");
      mail.To.Add("abcdef@yahoo.com");
      mail.IsBodyHtml = true;
      mail.Subject = "Registration";
      mail.Body = "Some Text";
      mail.Priority = MailPriority.High;
      
      SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
      //smtp.UseDefaultCredentials = true;
      smtp.Credentials = new System.Net.NetworkCredential("xyz@gmail.com", "<my gmail pwd>");
      smtp.EnableSsl = true;
      //smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
      
      smtp.Send(mail);
      

      但是,使用 gmail 存在问题。邮件将发送成功,但收件人收件箱中的“发件人地址”中的 gmail 地址,而不是代码中提到的“发件人地址”。

      要解决此问题,请按照以下链接中提到的步骤操作。

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

      在执行上述所有步骤之前,您需要验证您的 gmail 帐户以允许访问您的应用程序和设备。请在以下链接查看帐户认证的所有步骤:

      http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html

      【讨论】:

        【解决方案7】:
            ActiveUp.Net.Mail.SmtpMessage smtpmsg = new ActiveUp.Net.Mail.SmtpMessage();
            smtpmsg.From.Email = "abcd@test.com";
            smtpmsg.To.Add(To);
            smtpmsg.Bcc.Add("vijay@indiagreat.com");
            smtpmsg.Subject = Subject;
            smtpmsg.BodyText.Text = Body;
        
            smtpmsg.Send("mail.test.com", "abcd@sss.com", "user@1234", ActiveUp.Net.Mail.SaslMechanism.Login);
        

        【讨论】:

        • 一些关于你的解决方案会很好的话。
        【解决方案8】:

        简单的代码工作

        MailMessage mail = new MailMessage();
        mail.To.Add(to);
        mail.From = new MailAddress(from);
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient("smtp.gmail.com",587);
        smtp.EnableSsl = true;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential(address, password);
        smtp.Send(mail);
        

        【讨论】:

          猜你喜欢
          • 2011-08-01
          • 2013-04-02
          • 2012-01-07
          • 2023-03-19
          • 2017-05-12
          • 2015-09-28
          相关资源
          最近更新 更多