通过gmail使用System.Net.Mail发送电子邮件

57

我想通过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应用程序中的邮件域名。

谢谢...

3
发送邮件时,SMTP 服务器需要输入密码吗? - user541686
1
是的,Gmail的SMTP服务器需要身份验证。链接 - Cody Gray
1
兰伯特所说的。默认凭据与Windows相关。您需要为GMail指定它们。 - leppie
8个回答

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

2
几点观察:1.应该使用“smtp.gmail.com”,而不是“smtp.google.com”。我盯着我的代码看了半个小时,直到意识到我在使用后者。2.尽管我在这个主题上读到的所有其他内容都建议使用端口465,但端口587似乎要好得多。3.如果您正在使用两步验证,并且最好这样做(请参见http://www.codinghorror.com/blog/2012/04/make-your-email-hacker-proof.html),则必须为您的应用程序生成新密码。 - Bob Kaufman
2
顺便提一下,我遇到了这个问题:将SmtpClient对象放在using子句中。如果您要在循环中使用客户端,则必须这样做。 - Kyle
使用 using 子句是明智的,这样 smtpclient 就会“发送一个 QUIT 消息,然后优雅地结束 TCP 连接”。 - avgbody
这个解决方案(使用System.Net.Mail)对于隐式SSL(使用端口465)无效。您必须使用类似AbrahamJP的解决方案的其他方法。(http://blogs.msdn.com/b/webdav_101/archive/2008/06/02/system-net-mail-with-ssl-to-authenticate-against-port-465.aspx) - mdiehl13
更新 - 值得警告的是,此库现已被弃用!您能将此添加到您的答案中吗?https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.7.2 - Vincent Buscarello
显示剩余2条评论

12

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

在搜索时,我找到了一个类似的代码,它对我起作用。我将该代码在此发布。

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

字段是必需的吗? - Kiquenet
我从编译器收到的消息是 System.Web.Mail 方法已经被弃用。 - Su Llewellyn

7

设置

smtp.UseDefaultCredentials = false 

并使用

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

我也使用了这个答案。但是Sarwar的答案完全解决了我的问题。非常感谢,明天我会点赞的。干杯! - JCTLK

3
这是我的解决方案:

这对我有用:

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

您需要在“My account”谷歌安全/隐私设置中的“带有帐户访问权限的应用程序”选项中启用“允许不安全的应用程序” (https://myaccount.google.com)


3

我意识到这是对一个非常古老的问题的回答,并且已经有很多其他好的答案。我发布此代码以包含其他用户发布的有用评论,例如使用语句和一些答案中已过时的方法的更新方法。此代码在2018年7月11日进行了测试并且有效。

如果通过您的GMail帐户发送,请确保从您的控制面板启用允许不安全应用程序

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

1

使用端口号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


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

2
关于您的解决方案,一些说明会很好。 - Werner Henze

0

简单的代码运行正常

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接