Adsense

Sunday, March 04, 2007

Sending mail through Gmail Programatically - C# .Net VS2005 Gmail

I was implementing a simple Contact Us form for a friend's website that would allow users to shoot him an E-mail message from the site. You can send E-mail directly from a .Net application using an SMTP server, but most free web-based E-mail companies wont allow you to use their SMTP servers for stuff like this. I was delighted to find that you could get this working with Gmail. I'll show you a quick sample method that will allow you to do this.
Information You'll Need...
  1. Your Gmail information (Username, Password)
  2. The Gmail SMTP server address (smtp.gmail.com)
  3. The port Gmail uses (465 or 587)
Namespaces used...
  1. System.Net;
  2. System.Net.Mail;
  3. System.ComponentModel;
Key Objects...
  1. MailMessage
  2. SmtpClient
Your Configuration File
<appSettings> <add key="pswd" value="YourGmailPassword"/> <add key="account" value="yourUserName@gmail.com"/> <add key="host" value="smtp.gmail.com" /> </appSettings>
Implementing a simple SendMail method
public void SendMail(string host, int port, string userName, string pswd, string fromAddress, string toAddress, string body, string subject, bool sslEnabled) { MailMessage msg = new MailMessage(new MailAddress(fromAddress), new MailAddress(toAddress)); // Create a MailMessage object with a from and to address msg.Subject = subject; // Add your subject msg.SubjectEncoding = System.Text.Encoding.UTF8; msg.Body = body; // Add the body of your message msg.BodyEncoding = System.Text.Encoding.UTF8; msg.IsBodyHtml = false; // Does the body contain html SmtpClient client = new SmtpClient(host, port); // Create an instance of SmtpClient with your smtp host and port client.Credentials = new NetworkCredential(userName, pswd); // Assign your username and password to connect to gmail client.EnableSsl = sslEnabled; // Enable SSL try { client.Send(msg); // Try to send your message ShowMailMessage("Your message was sent successfully.", false); // A method to update a ui element with a message Clear(); } catch (SmtpException ex) { ShowMailMessage(string.Format("There was an error sending you message. {0}", ex.Message), true); } }


Calling your SendMail method

public void imgSubmit_Click(object sender, EventArgs e) { string pswd = ConfigurationManager.AppSettings["pswd"]; // Your Password string account = ConfigurationManager.AppSettings["account"]; // Your account name (username@gmail.com) string host = ConfigurationManager.AppSettings["host"]; // Your smtp server name (smtp.gmail.com) int port = 587; // The port used to connect to your host if (string.IsNullOrEmpty(pswd) || string.IsNullOrEmpty(account) || string.IsNullOrEmpty(host)) // Validate App Settings ShowMailMessage("Unable to send your message. Configuration Error.", true); else { SendMail(host, port, account, pswd, txtFrom.Text, account, txtBody.Text, txtSubject.Text, true); } }
That's pretty much all there is to it. Your user fills out the form and clicks submit, and you get an E-mail in your Gmail box, send through your Gmail Account

21 comments:

Jordan said...

umm...why did you post this at 4:30 in the freakin' morning?!

perezj said...

Thanks for your post. I re-used your code to create a little app that allows me to send attachements from my windows explorer to any gmail account.

Know I can right click on any file and select Send To Gmail and email the selected file as an attachement.

Jesper said...

Please let us have that program. Nowhere i have been able to find a rightclick-sendto files to gmail contacts...

Kindly Jesper, Denmark
q@jesperkjems.dk

Unknown said...

I used these codes, I am getting the sending failed msg.
why?
Please Help me to solve this problem.

dyetube said...

Thanks for the great code! Works like a charm! Whats the correct formatting for sending to multiple recipients? I tried using a comma as a seperator with no luck and when I use a semicolon it errors out. Thanks!

Jeff McBride
Web developer
www.solarmecca.com

Paul Fox said...

Thanks Jeff,

The MailMessage object has a collection of To address. You should be able to add multiple MailAddress objects to the message using the following.

MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("me@here.now"));
msg.To.Add(new MailAddress("you@there.now"));

Hope this helps. =)

dyetube said...

Thanks! Have you ever encountered time out erros with this? It was working fine and now for some reason I am getting time out errors... I have been testing so I have been sending out numerous emails and thought that maybe google thought I was spamming (even though I was only sending to 3 addresses). Thanks again!

Jeff McBride
Web Developer
www.solarmecca.com

Paul Fox said...

I haven't encountered any time-out errors with this process, but I've only used it on a small site that sent one or two messages a day.

I wouldn't imagine that Google would interfere, think you were spamming, unless your usage was quite excessive. But its possible.

~ Paul

dyetube said...

O.k... I'll recheck my code as I cahn ged some things to try a different smtp. Thanks!

dyetube said...

Figured it out... Thanks for the help!

Unknown said...

Thanks, It also worked for me

Anonymous said...

Thanks for the CODE, It helped.

Actually itried both the methods before this

The System.Web.Mail one and the System.Net.Mail one.

But the point was I was lacking the Authentication.

עוז said...

wow! that really worked! Thanks for the help, You Think - therefore we earn.

Paul Fox said...

I'm glad it helped. I recently had to come back to this post to implement this for another project I'm working on.

I knew I wrote these for a reason! =)

Anonymous said...

Thank you very much, this was exactly what I was looking for!

Great, simple code and it just works.

Snowmicro Technologies said...
This comment has been removed by the author.
Snowmicro Technologies said...

Thanks , it's working..

Johnny T Bjerring said...

If you get a timeout error, try using the other port. helped for me :-D

Unknown said...

Thank You Very Much Sir !
Its Working fine for me !

bhargav said...

sir i am getting sending failed pls help me out i am not using app.config
i am send parms dir is this the problem

Anonymous said...

Thanks very much for this code. I used it and modified a few lines to suit our requirement. It worked very smooth. Thank you.