57

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....

MailMessage mail = new MailMessage();

mail.From = new System.Net.Mail.MailAddress("[email protected]");

//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("[email protected]"));

//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...

3
  • 3
    Don't you need to enter your password somewhere for the SMTP server? Commented Jan 13, 2011 at 6:14
  • 1
    Yes, Gmail's SMTP server requires authentication. Link Commented Jan 13, 2011 at 6:15
  • 1
    What Lambert said. Default credentials is Windows related. You would need to specify them for GMail. Commented Jan 13, 2011 at 6:15

8 Answers 8

82
+50
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("[email protected]");

// 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("[email protected]"));

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

mail.Body = st;
smtp.Send(mail);
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks Sarwar... Your guess with the port is correct. I will upvote this tomorrow.
A few observations: 1. It's "smtp.gmail.com", not "smtp.google.com". I was staring at my code for half an hour until I realized I was using the latter. 2. Port 587 seems to work a lot better than 465 even though everything else I've read on the subject says to use port 465. 3. If you're using two-step verification, and you'd better be (see codinghorror.com/blog/2012/04/make-your-email-hacker-proof.html) you must generate a new password for your application.
FYI, as I ran into this: Enclose your SmtpClient object in a using clause. You must do this especially if you're going to be using the client in a loop.
Using a using clause would be wise so that the smtpclient " sends a QUIT message followed by gracefully ending the TCP connection".
This solution (using System.Net.Mail) doesn't work for implicit SSL (using port 465). You must use something else like AbrahamJP's solution. (blogs.msdn.com/b/webdav_101/archive/2008/06/02/…)
|
12

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

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 = "[email protected]";
        string pGmailPassword = "GmailPassword";
        string pTo = "ToAddress"; //[email protected]
        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);
    }
}

2 Comments

Fields are necessary ?
I am getting the message from the compiler that the System.Web.Mail methods are deprecated.
7

Set

smtp.UseDefaultCredentials = false 

and use

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

1 Comment

I used this answer also. But Sarwar's answer completely solved my problem. Thanks alot and I will upvote this tomorrow. Cheers.
3

This have worked for me:

        MailMessage message = new MailMessage("[email protected]", 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("[email protected]", "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)

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)

Comments

3

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.

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

Class Code 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:

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#:

{
Email em = new Email();
em.NewHeadlessEmail("[email protected]", "password", "[email protected]", "Subject Text", "Body Text");
}

Usage VB:

Dim em As New Email
em.NewHeadlessEmail("[email protected]", "password", "[email protected]", "Subject Text", "Body Text")

Comments

1

Use Port number 587

With the following code, it will work successfully.

MailMessage mail = new MailMessage();
mail.From = new MailAddress("[email protected]", "Enquiry");
mail.To.Add("[email protected]");
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("[email protected]", "<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.

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

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:

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

Comments

0
    ActiveUp.Net.Mail.SmtpMessage smtpmsg = new ActiveUp.Net.Mail.SmtpMessage();
    smtpmsg.From.Email = "[email protected]";
    smtpmsg.To.Add(To);
    smtpmsg.Bcc.Add("[email protected]");
    smtpmsg.Subject = Subject;
    smtpmsg.BodyText.Text = Body;

    smtpmsg.Send("mail.test.com", "[email protected]", "user@1234", ActiveUp.Net.Mail.SaslMechanism.Login);

1 Comment

Some words about what your solution would be nice.
0

simple code works

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.