ForeverZer0

CSharp Send Email

Feb 12th, 2012
180
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System.Net.Mail;
  2.  
  3. namespace EmailExample
  4. {
  5.     public class Email
  6.     {
  7.         /// <summary>
  8.         /// Uses Gmail to send an email
  9.         /// </summary>
  10.         /// <param name="recipient">The email address the message will be sent to</param>
  11.         /// <param name="subject">The subject of the email</param>
  12.         /// <param name="text">The body of the email</param>
  13.         /// <returns>Flag if email was sent successfully or not</returns>
  14.         public static bool SendEmail(string recipient, string subject, string text)
  15.         {
  16.             try
  17.             {
  18.                 MailMessage mail = new MailMessage();
  19.                 SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
  20.                 // Use your actual email address
  21.                 mail.From = new MailAddress("<your_email_address@gmail.com>");
  22.                 mail.To.Add(recipient);
  23.                 mail.Subject = subject;
  24.                 mail.Body = text;
  25.                 SmtpServer.Port = 587;
  26.                 // Use your actual username and password
  27.                 SmtpServer.Credentials =
  28.                     new System.Net.NetworkCredential("<username>", "<password>");
  29.                 SmtpServer.EnableSsl = true;
  30.                 SmtpServer.Send(mail);
  31.                 return true;
  32.             }
  33.             catch
  34.             {
  35.                 return false;
  36.             }
  37.         }
  38.     }
  39. }
RAW Paste Data