Saturday, July 10, 2021

GMAIL SMTP Server using C# and VB.Net

GMAIL SMTP Server using C# and VB.Net

In this article I will explain with an example, how to send email using GMAIL SMTP Server using C# and VB.Net.

App.Config AppSettings

Following are the SMTP settings which are saved inside the AppSettings section of the App.Config file.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <appSettings>

        <add key="Host" value="smtp.gmail.com"/>

        <add key="Port" value="587"/>

        <add key="SSL" value="true"/>

        <add key="FromEmail" value="sender@gmail.com"/>

        <add key="Username" value="sender@gmail.com"/>

        <add key="Password" value="password"/>

    </appSettings>

</configuration>

Namespaces 

You will need to import the following namespaces.

C#

using System.IO;

using System.Net;

using System.Net.Mail;

using System.Configuration;

 

VB.Net

Imports System.IO

Imports System.Net

Imports System.Net.Mail

Imports System.Configuration

Sending SMTP email using Console Application

When the Program is run, the values of Recipient email address (To), Subject and Body is read as input from the User.

While the Sender email address (from) is read from the FromEmail AppSettings key.

Then all these values are set into an object of the MailMessage class.

Then an object of SmtpClient class is created and the settings of the GMAIL SMTP server i.e. Host, Username, Password and Port are read from the respective AppSetting keys.

Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be equal to Gmail Username specified in credentials.

Finally the email is sent using the Send function of the SmtpClient class object.

MailMessage Class Properties

Following are the required properties of the MailMessage class.

From – Sender’s email address.

To – Recipient(s) Email Address.

CC – Carbon Copies (if any).

BCC – Blind Carbon Copies (if any).

Subject – Subject of the Email.

Body – Body of the Email.

IsBodyHtml – Specify whether body contains text or HTML mark up.

Attachments – Attachments (if any).

ReplyTo – ReplyTo Email address.

 

SmptClient Class Properties

Following are the properties of the SmtpClient class.

Host – SMTP Server URL (Gmail: smtp.gmail.com).

EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True).

UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails.

Credentials – Valid login credentials for the SMTP server (Gmail: email address and password).

Port – Port Number of the SMTP server (Gmail: 587)

C#

namespace Send_Email_Console_CS

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Enter To Address:");

            string to = Console.ReadLine().Trim();

 

            Console.WriteLine("Enter Subject:");

            string subject = Console.ReadLine().Trim();

 

            Console.WriteLine("Enter Body:");

            string body = Console.ReadLine().Trim();

 

            using (MailMessage mm = new MailMessage(ConfigurationManager.AppSettings["FromEmail"], to))

            {

                mm.Subject = subject;

                mm.Body = body;

                mm.IsBodyHtml = false;

                SmtpClient smtp = new SmtpClient();

                smtp.Host = ConfigurationManager.AppSettings["Host"];

                smtp.EnableSsl = true;

                NetworkCredential NetworkCred = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"]);

                smtp.UseDefaultCredentials = true;

                smtp.Credentials = NetworkCred;

                smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);

                Console.WriteLine("Sending Email......");

                smtp.Send(mm);

                Console.WriteLine("Email Sent.");

                System.Threading.Thread.Sleep(3000);

                Environment.Exit(0);

            }

        }

    }

}

 

VB.Net

Module Module1

    Sub Main()

        Console.WriteLine("Enter To Address:")

        Dim [to] As String = Console.ReadLine().Trim()

 

        Console.WriteLine("Enter Subject:")

        Dim subject As String = Console.ReadLine().Trim()

 

        Console.WriteLine("Enter Body:")

        Dim body As String = Console.ReadLine().Trim()

 

        Using mm As New MailMessage(ConfigurationManager.AppSettings("FromEmail"), [to])

            mm.Subject = subject

            mm.Body = body

            mm.IsBodyHtml = False

            Dim smtp As New SmtpClient()

            smtp.Host = ConfigurationManager.AppSettings("Host")

            smtp.EnableSsl = True

            Dim NetworkCred As New NetworkCredential(ConfigurationManager.AppSettings("Username"), ConfigurationManager.AppSettings("Password"))

            smtp.UseDefaultCredentials = True

            smtp.Credentials = NetworkCred

            smtp.Port = Integer.Parse(ConfigurationManager.AppSettings("Port"))

            Console.WriteLine("Sending Email......")

            smtp.Send(mm)

            Console.WriteLine("Email Sent.")

            System.Threading.Thread.Sleep(3000)

            Environment.Exit(0)

        End Using

    End Sub

End Module

No comments:

Post a Comment

DotNet Latest Technologies

  I'm not sure exactly what you are looking for or how "recent" the technologies that you might wan to look into are, but I...