Send Gmail using Dot NET

Hi, in my previous posts, I have posted how to send mail using the Java API. In this section, I would like to demonstrate on how to send mail using Dot NET.
Using Dot NET, it is equally easy to send mail. In this post I would use my Dot NET application to connect with Google's outgoing mail server (Google's SMTP server) and use that to forward my mail. (In my previous post, I've demonstrated on sending mail using my own SMTP server which ran on my machine. In this scenario, it will directly put the outgoing message into the Gmail's SMTP server)

You will be using mainly few Classes to get the job done.

System.Net.Mail.MailMessage
System.Net.NetworkCredential

System.Net.Security.SmtpClient


These classes will provide the basic methods to get the job done.
You will also be using System.Net.Mail.MailAddress class. (Though there is a way to get the job done without actually needing this.)

First of all, you need to import the namespaces.

using System.Net.Mail;
using System.Net;

using System.Net.Security;


Now, create a MailMessage object using the following LOC.

MailMessage mail = new MailMessage();

Now, lets set the sender's address and receiver's address. We create a MailAddress object and set the value directly from its constructor.

mail.From = new MailAddress("from@gmail.com","Any name to appear as alias");

Now set the receiver.

mail.To.Add(new MailAddress("toaddress", "
Any name to appear as alias"));

NOTE: You cannot simply set the To Address in a similar way as setting from address. ie: You cannot set
mail.To=new MailAddress("yourffiend", "Alias name");
This is because, you can send a mail to multiple people at once. Hence, the To property of a mail object contains a collection of MailAddress objects. You can add a new mail address to the collection in the above manner.

Now create an SmtpClient object. This can be done using.

SmtpClient smtp = new SmtpClient();


Next, we will set the host address of the smtp server.

smtp.Host = "smtp.gmail.com";

And the port.

smtp.Port = 587;


NOTE: If you are using your own SMTP mail server, then the port would be port 25.

We will use our own credentials. Thus disable the default credentials.

smtp.UseDefaultCredentials = false;

We
must enable SSL.

smtp.EnableSsl = true;


Now we will create our own credentials using the following LOC.
First create a NetworkCredential object.

NetworkCredential cred = new NetworkCredential();


And now set the required usename and password.

cred.UserName = "username";

cred.Password="password";

And now , set the credentials of the smtp object to the credentials we created.

smtp.Credentials = cred;

Now, you can send the main using the follwing LOC.

smtp.Send(mail);

I have taught you the basic procedure, now you can extend it to get the job done your way. Have fun Folks !!!!

Comments

Popular posts from this blog

Encrypt and Decrypt Images Using Java

Build your own Network sniffer

ASP Response.Write newline