Thursday, January 31, 2013

Send mail from your gmail account with C#

I'm currently working on a new project. I'm supposed to read from a USB temperature sensor, and log the temperature. And if the temperature is below a certain threshold temperature the application will warn the client thru mail.


And so now i have at least gotten the SendMail class working, and ready for implementation with the rest of the program. So here is the source code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;

namespace TempNET
{
    class SendMail
    {
        public string sendMail(string recieverMailAddress, string recieverName, string messageSubject, string messageBody)
        { // method for sending mail
            try
            {
                // using a GMail account
                var fromAddress = new MailAddress("gmailaccount@gmail.com", "Senders name"); 
                var toAddress = new MailAddress(recieverMailAddress, recieverName);
                const string fromPassword = "gmailaccount password";

                // create smtp client object containing all needed info
                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                // create mail
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = messageSubject,
                    Body = messageBody
                })
                {
                    smtp.Send(message);
                }
                // mail sendt successfully
                return "Mail sendt";
            }
            catch (Exception ex)
            {
                // something failed, return error message
                return "Error: " + ex.Message;
            }
        }
    }
}

No comments:

Post a Comment