Mail This!!!

I am sure many of you might have come across situations where you want to send mail from your application. I will be sharing a bit of code that will help you in this.
For sending a mail all we need is a SMTP(Simple Mail Transfer Protocol) Server which we will be getting it for free from GMAIL.(smtp.gmail.com)
Now to use this server we need credentials to this server. There is no big deal in getting these credentials you only need to have a gmail account.(Which also is free :))

OK now we got all the essential ingredients, lets start coding....

Sending mail is in C# .NET is straight forward.Its all there in System.Net.Mail and System.Net namespaces.Now to connect to a server we need a client object which is instantiated from the System.Net.Mail.SmtpClient class.

To setup the properties of a SMTP client you might want to refer this.



SmtpClient emailClient = new SmtpClient("smtp.gmail.com");


The argument passed to the constructor is the SMTP server host.


System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential("xyz@gmail.com","*******"); 
            emailClient.EnableSsl = true;
            emailClient.Credentials = SMTPUserInfo;
            emailClient.Port = 587;



NetwotkCredential Class is used to authenticate our username and password of Gmail account.

We are done with the SMTP server settings.Now we will have to prepare the message that is to be sent to the recipient.
To compose a message System.Net.Mail.MailMessage Class is used.


MailMessage message = new System.Net.Mail.MailMessage("xyz@gmail.com""someone@something.something""fire!!""Call up 911 and inform my house is on fire and my phone too");


Argument 1: From mail id.
Argument 2: To mail id.
Argument 3: Subject of the message.
Argument 4: Content of the message.

We are all done.......Oh no wait did'n send it yet.


emailClient.Send(message);


That's it.

You can use this piece of code in a lot of ways. Here is a simple demo application that will help zip and attach multiple files in a folder by just right clicking on it.

Binary
Source code

To use this app you will have to do the following.
1. Run SendMail.exe.
2.Click on Settings You should see this

3.Fill the textboxes and then Click on the save icon.

4.Click on "Add Context Menu" button, if you would want to see this in your folder context menu.

5.Now to mail multiple files zipped and attached you just need to group the files to be mailed in a folder and right click "MailThis".


This is just a sample app you can use the same code to serve your need.

NOTE: This app requires administrator privilege to add context menu.


Its monday morning and i am posting a blog entry, don't you think i am jobless. ;)

Comments are welcome and please feel free to correct me if am wrong.

Comments

Popular posts from this blog

Launch .Net Core with VSCode for starters

Protecting sensitive data using Secret Manager in .Net Core

Load Testing an nodejs API