Send Email using Gmail with Attachment in Asp.Net C# VB.Net

E-mail is one of the most common popular methods of communication for both personal and business purposes. It also plays an important role in each and every Web site specially for registration page or sales order page of an e-commerce site & also for online invoicing. The .NET framework makes the task of sending email from a Web page unbelievably easy and I’ll show you how to do it in a matter of minutes.

Here I am using Gmail SMTP to send email using Asp.Net C# VB.Net cause i think most of the reader has a Gmail id so that he can just copy the below code and can start sending email. Just need to change the from and credentials. Better first try with Gmail cause its easy to test. Then go for your own mail server.

To do the example first add some HTML markup like below:

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <b>To</b><br />
    <asp:TextBox ID="txtTo" runat="server"></asp:TextBox><br />
    <b>Subject:</b><br />
    <asp:TextBox ID="txtSubject" runat="server"></asp:TextBox><br />
    <b>Message:</b><br />
    <asp:TextBox ID="txtMessage" runat="server" Columns="50" Rows="10" 
        TextMode="MultiLine"></asp:TextBox><br />
    <asp:Label ID="lblStatus" runat="server" Text="" Font-Bold="true"></asp:Label><br />
    <asp:Button ID="cmdSend" runat="server" Text="Send Mail" 
        onclick="cmdSend_Click" />
</asp:Content>

Send Email to Multiple Recipient:
C# Code:

    protected void cmdSend_Click(object sender, EventArgs e)
    {
        MailMessage mailMsg = new MailMessage();
        string[] split = txtTo.Text.Split(new Char[] { ' ', ',', ';'});

        // if you want to send HTML BODY then true for plain text body use false
        mailMsg.IsBodyHtml = true;
        mailMsg.Subject = txtSubject.Text;
        mailMsg.Body = txtMessage.Text;
        mailMsg.From = new MailAddress("shawpnendu@gmail.com");
        //mailMsg.Attachments.Add(new Attachment("c:\\abc.txt"));

        foreach (string sTo in split)
            if (sTo.Trim() != "")
                mailMsg.To.Add(sTo);
        
        SmtpClient smtp = new SmtpClient("smtp.gmail.com");
        smtp.Port = 587;
        smtp.Credentials = new System.Net.NetworkCredential("shawpnendu@gmail.com", "your password");
        // If you use your smtp server then try first with blocking the below line.
        smtp.EnableSsl = true;
        smtp.Send(mailMsg);
        lblStatus.Text = "Mail Sent successfully !!";
    }

Note: Don’t forget to add “System.Net.Mail” namespace. To send email to multiple recipient you can use space, comma or semicolon as email address separator in “To” TextBox.

VB.Net:

    Protected Sub cmdSend_Click(sender As Object, e As System.EventArgs) Handles cmdSend.Click
        Dim mailMsg As New MailMessage()

        ' if you want to send HTML BODY then true for plain text body use false
        mailMsg.IsBodyHtml = True
        mailMsg.Subject = txtSubject.Text
        mailMsg.Body = txtMessage.Text
        mailMsg.From = New MailAddress("shawpnendu@gmail.com")
        mailMsg.[To].Add(txtTo.Text)
        Dim smtp As New SmtpClient("smtp.gmail.com")
        smtp.Port = 587
        smtp.Credentials = New System.Net.NetworkCredential("shawpnendu@gmail.com", "your password")
        ' If you use your smtp server then try first with blocking the below line.
        smtp.EnableSsl = True
        smtp.Send(mailMsg)
        lblStatus.Text = "Mail Sent successfully !!"

    End Sub

Note: Don’t forget to add “System.Net.Mail” namespace. To send email to multiple recipient you can use space, comma or semicolon as email address separator in “To” TextBox.

Now run the project hope you can successfully send Email like below:
Send Email using Gmail in Csharp VB.Net

Send Email with Attachment:
C# Code:

mailMsg.Attachments.Add(new Attachment("c:\\abc.txt"));

Note: Just add this code under mailMsg.From line. For multiple attachments Add multiple lines with path.

VB.Net Code:

mailMsg.Attachments.Add(new Attachment("c:\\abc.txt"))

Note: Just add this code under mailMsg.From line. For multiple attachments Add multiple lines with path.

Good to Know:
If you are going to host your web site then ask administrator the below questions:
1. Does mail server configured? If yes then collect smtp server name & replace with smtp.gmail.com
2. Does the mail server require authentication before sending an email? If yes then modify credentials else remove credential line from above code segment.
3. Does the mail server relay is on? If no then make it yes.
4. Does the mail server require SSL validation. If no then remove EnableSSL line.

Common error message:
1. Mailbox unavailable. The server response was: 5.7.1 Unable to relay for…………..
Resolution: Need to configure the SMTP server to allow relaying for either your IP, “FROM” address, or credentials. Notify hosting server administrator to allow the relay against your From email address. If you are using localhost then right click on mycomputer then manage then services & applications then IIS then right click on default SMTP virtual server then properties then click on access tab then click on relay button then select only the list below then click on ADD & set the IP 127.0.0.1

2. The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
Send Email Error 1

Resolution: Check your gmail inbox. You received an email with “Google Account: sign-in attempt blocked” subject. Open the mail. Go to “https://www.google.com/settings/security/lesssecureapps“. Set Enable Radio Button will resolve your problem. For your convinient:

Send Email Error Resolution

Download Code Example C#        Download Code Example VB.Net

One thought on “Send Email using Gmail with Attachment in Asp.Net C# VB.Net

  • February 4, 2017 at 4:32 am
    Permalink

    Why does everyone have to set all gmail account’s to “less secure”? Is VB.NET never able to send a secure email (by google’s definition).

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code