Results 1 to 2 of 2

Thread: Code to send an email via SSL and Gmail

Threaded View

  1. #1

    Code to send an email via SSL and Gmail

    This is C# 2010 code to run as a console application (you can try it with MS Visual C# 2010 Express):

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Mail;
    
    
    namespace gmailsend
    {
        class Program
        {
            static void Main(string[] args)
            {
                string from = "me@dfgr.com"; //Replace this with your own correct Gmail Address
    
    
                MailAddress to = new MailAddress("fred@xzc.wx", ""); //Replace this with the Email Address to whom you want to send the mail
    
    
                MailMessage mail = new MailMessage();
                mail.To.Add(to);
                mail.From = new MailAddress(from, "Bilbo", System.Text.Encoding.UTF8);
                mail.Subject = "This is a test mail" ;
                mail.SubjectEncoding = System.Text.Encoding.UTF8;
                mail.Body = "This is Email Body Text";
                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.IsBodyHtml = false ;
                mail.Priority = System.Net.Mail.MailPriority.High;
    
    
                SmtpClient client = new SmtpClient();
                //Add the Creddentials- use your own email id and password
    
    
                client.Credentials = new System.Net.NetworkCredential(from, "your-gmail-password");
    
    
                client.Port = 587; // Gmail works on this port
                client.Host = "smtp.gmail.com";
                client.EnableSsl = true; //Gmail works on Server Secured Layer
               try
                {
                    client.Send(mail);
                    Console.WriteLine("Message sent.");
                }
                catch (Exception ex) 
                {
                    Exception ex2 = ex;
                    string errorMessage = string.Empty; 
                    while (ex2 != null)
                    {
                        errorMessage += ex2.ToString();
                        ex2 = ex2.InnerException;
                    }
                    Console.WriteLine(errorMessage );
                } // end try 
            }
        }
    }
    To run the compiled code (after you developed it into a useful app.) on a server, you would need to install the dot net 2010 run time distribution code.
    Last edited by Andy101; 11 April, 2013 at 11:15 AM. Reason: more detail added

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •