C# .NET - Email through Gmail in C# - Asked By Tom O'B on 14-Mar-07 09:11 AM

Anyone have any luck sending emails through gmail accounts in C# applications? I can't get it to work. .

Thanks in advance,

Tom.

Why don't you explain what you can't get to work. - Robert Stanton replied to Tom O'B on 14-Mar-07 10:10 AM

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("tom@gmail.com", "tomsPassword");

mail.To.Add("helpneeded@egghead.com");
mail.Subject = "tom needs some gmail help";

mail.From = new System.Net.Mail.MailAddress("tom@gmail.com");
mail.IsBodyHtml = true;
mail.Body = "this is the body of the message";

System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Port = 587;
smtp.Send(mail);


Why don't you explain what you can't get to work - Tom O'B replied to Robert Stanton on 14-Mar-07 10:42 AM

Thanks for the swift reply, Robert.

I just put that method into the Form_Load method of my class, but I get an exception: Failure to send mail. Is it something to do with the port or something? I had a similar method, but it wouldn't work either.

This is what I had:

System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("sender@gmail.com", "recipient@gmail.com","This is the mail subject", "Just wanted to say Hello");
MyMailMessage.IsBodyHtml = false;
System.Net.NetworkCredential mailAuthentication = new
System.Net.NetworkCredential("sender@gmail.com", "password");
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
mailClient.Send(MyMailMessage);

And I'm getting the following. . . . . .

System.Net.Mail.SmtpException was unhandled
  Message="Failure sending mail."
  Source="System"
  StackTrace:
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at EmailTest.Form1.SendMail1() in C:\Documents and Settings\tobriain\Local Settings\Application Data\Temporary Projects\EmailTest\Form1.cs:line 52
       at EmailTest.Form1.Form1_Load(Object sender, EventArgs e) in C:\Documents and Settings\tobriain\Local Settings\Application Data\Temporary Projects\EmailTest\Form1.cs:line 24
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Control.set_Visible(Boolean value)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at EmailTest.Program.Main() in C:\Documents and Settings\tobriain\Local Settings\Application Data\Temporary Projects\EmailTest\Program.cs:line 17
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

How can I debug what's going on a little better. Maybe my SMTP setup isn't suitable.

Thanks in advance,

Tom.

Different port? - Sean Patterson replied to Tom O'B on 14-Mar-07 11:10 AM

Some of the documentation I'm reading requires the connection to the GMail SMTP server be conntected over port 465. Could that be your issue?
Different port? - Tom O'B replied to Sean Patterson on 14-Mar-07 11:39 AM
I tried a few different ports, but no luck. I think I have gotten somewhere though, because if I try to set up Outlook Express to send or collect mail from my account, I'm getting an error message. . ..

The connection to the server has failed. Account: 'pop.gmail.com', Server: 'smtp.gmail.com', Protocol: SMTP, Port: 465, Secure(SSL): Yes, Socket Error: 10060, Error Number: 0x800CCC0E

So I think there is something else going on, but don't know what.

Any help is much appreciated,

Tom.


Socket Error could be the issue... - Sean Patterson replied to Tom O'B on 14-Mar-07 01:40 PM
Interesting to note is that the socket error (10060) is consistent with an ISP blocking outside SMTP sends. A lot of ISPs are doing that to prevent spamming since they want to control what e-mails flow out. Do you know if your environment is setup that way? You may need to find an alternate way to get into a DMZ or something to test outgoing e-mail.

Just as a sidenote, if if hasn't been mentioned already, http://systemnetmail.com is a GREAT resource for dealing with sending e-mail in .NET They also have a nice list of items to check when debugging mail errors.



C# email from Gmail - lee suko replied to Tom O'B on 16-Jun-09 02:36 AM

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

                mail.From = new MailAddress("your_email_address@gmail.com");
                mail.To.Add("to_address@mfc.ae");
                mail.Subject = "Test Mail";
                mail.Body = "This is for testing SMTP mail from GMAIL";

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
                SmtpServer.EnableSsl = true;

http://csharp.net-informations.com/communications/csharp-smtp-mail.htm

lee.

christian paredes valdivia - christian paredes valdivia replied to lee suko on 10-Aug-09 05:26 PM

http://www.mono-project.com/FAQ:_Security


Does SSL works for SMTP, like GMail ?

Yes it does. First you must import the root certificates using the mozroots tool:

mozroots --import --ask-remove 

Note that if you are using a web application (i.e. not the current user) you must add the --machine option like this:

mozroots --import --ask-remove --machine

Next you need to import the intermediate certificates. You can do this by using the certmgr tool to connect to the SSL server. E.g.

certmgr -ssl smtps://smtp.gmail.com:465

Use the -m option to import the certificates into the machine store if required.

Finally you need to make sure to use the SSL-enabled port in your application. This is generally 465 or 587 instead of port 25.

Nathan replied to Tom O'B on 24-Mar-10 02:17 PM
You can follow the directions that I found on this blog to setup mail in a .Net application using a Gmail account.

http://foxsys.blogspot.com/2007/03/send-mail-in-your-net-application-using.html

I've used this in several applications and it works great.
Anoop S replied to Sean Patterson on 20-Jul-11 01:04 AM
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