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

时间:2022-05-13 18:15:08

I want to send a email through gmail server. I have put the following code but it is getting stuck while sending. Any idea please....

我想通过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);

The xxxx.com is a mail domain in Google apps. Thanks...

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

7 个解决方案

#1


71  

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


11  

I tried the above C# code to send mail from Gmail to my Corporate ID. While executing the application the control stopped indefinitely at the statement smtp.Send(mail);

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

While Googling, I came across a similar code, that worked for me. I am posting that code here.

谷歌搜索时,我遇到了类似的代码,对我有用。我在这里发布该代码。

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

#3


7  

Set smtp.UseDefaultCredentials = false and use smtp.Credentials = new NetworkCredential(gMailAccount, password);

设置smtp.UseDefaultCredentials = false并使用smtp.Credentials = new NetworkCredential(gMailAccount,password);

#4


2  

This have worked for me:

这对我有用:

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

BUT (as of the time of this writing - Oct 2017)

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

You need to ENABLE "Allow less secure apps" inside the option "apps with account access" at the "My account" google security/privacy settings (https://myaccount.google.com)

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

#5


0  

Use Port number 587

使用端口号587

With the following code, it will work successfully.

使用以下代码,它将成功运行。

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

But, there is a problem with using gmail. The email will be sent successfully, but the recipient inbox will have the gmail address in the 'from address' instead of the 'from address' mentioned in the code.

但是,使用Gmail有一个问题。电子邮件将成功发送,但收件人收件箱中的gmail地址将位于“发件人地址”中,而不是代码中提到的“发件人地址”。

To solve this, please follow the steps mentioned at the following link.

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

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

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

before following all the above steps, you need to authenticate your gmail account to allow access to your application and also the devices. Please check all the steps for account authentication at the following link:

在执行上述所有步骤之前,您需要对您的Gmail帐户进行身份验证,以允许访问您的应用程序以及设备。请通过以下链接检查帐户身份验证的所有步骤:

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

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

#6


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

#7


0  

I realise this is an answer to a very old question, with lots of other good answers. I am posting this code to include some of the useful comments posted by other users such as Using Statements and newer methods where some answers have obsolete methods. This code was tested and working as of 11 July 2018.

我意识到这是一个非常古老的问题的答案,还有很多其他好的答案。我发布此代码以包含其他用户发布的一些有用的注释,例如使用语句和更新的方法,其中一些答案具有过时的方法。此代码已于2018年7月11日进行测试和工作。

If sending via your GMail Account ensure that Allow less secure apps is enabled from your control panel

如果通过您的GMail帐户发送,请确保通过控制面板启用了“安全性较低的应用”

Class Code C#:

类代码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);
        }
    }
}
}

Class Code VB:

类代码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

Usage C#:

用法C#:

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

Usage VB:

用法VB:

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

#1


71  

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


11  

I tried the above C# code to send mail from Gmail to my Corporate ID. While executing the application the control stopped indefinitely at the statement smtp.Send(mail);

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

While Googling, I came across a similar code, that worked for me. I am posting that code here.

谷歌搜索时,我遇到了类似的代码,对我有用。我在这里发布该代码。

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

#3


7  

Set smtp.UseDefaultCredentials = false and use smtp.Credentials = new NetworkCredential(gMailAccount, password);

设置smtp.UseDefaultCredentials = false并使用smtp.Credentials = new NetworkCredential(gMailAccount,password);

#4


2  

This have worked for me:

这对我有用:

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

BUT (as of the time of this writing - Oct 2017)

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

You need to ENABLE "Allow less secure apps" inside the option "apps with account access" at the "My account" google security/privacy settings (https://myaccount.google.com)

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

#5


0  

Use Port number 587

使用端口号587

With the following code, it will work successfully.

使用以下代码,它将成功运行。

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

But, there is a problem with using gmail. The email will be sent successfully, but the recipient inbox will have the gmail address in the 'from address' instead of the 'from address' mentioned in the code.

但是,使用Gmail有一个问题。电子邮件将成功发送,但收件人收件箱中的gmail地址将位于“发件人地址”中,而不是代码中提到的“发件人地址”。

To solve this, please follow the steps mentioned at the following link.

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

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

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

before following all the above steps, you need to authenticate your gmail account to allow access to your application and also the devices. Please check all the steps for account authentication at the following link:

在执行上述所有步骤之前,您需要对您的Gmail帐户进行身份验证,以允许访问您的应用程序以及设备。请通过以下链接检查帐户身份验证的所有步骤:

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

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

#6


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

#7


0  

I realise this is an answer to a very old question, with lots of other good answers. I am posting this code to include some of the useful comments posted by other users such as Using Statements and newer methods where some answers have obsolete methods. This code was tested and working as of 11 July 2018.

我意识到这是一个非常古老的问题的答案,还有很多其他好的答案。我发布此代码以包含其他用户发布的一些有用的注释,例如使用语句和更新的方法,其中一些答案具有过时的方法。此代码已于2018年7月11日进行测试和工作。

If sending via your GMail Account ensure that Allow less secure apps is enabled from your control panel

如果通过您的GMail帐户发送,请确保通过控制面板启用了“安全性较低的应用”

Class Code C#:

类代码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);
        }
    }
}
}

Class Code VB:

类代码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

Usage C#:

用法C#:

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

Usage VB:

用法VB:

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