How To Send An Email Using C#



TODO:

Have you ever wanted to send an email in C#?

 

SOLUTION:

 

public bool sendEmail(string pstrTo, string Name, string bcc, string smtpServer, string smtpUser,
                                string pstrSubject, string strMessage, string attachFilePath)
        {
            string smtpServerPort = "25";
            MailMessage mailMsg = null;
            
            int port = 0;
            try
            {
                //make sure we have an email address.....
                if (String.IsNullOrEmpty(pstrTo))
                    throw new Exception("Email address was not supplied");

                //get smtp user, and make sure its valid
                if (String.IsNullOrEmpty(smtpServer))
                    throw new Exception("No SMTP Server specified");

                port = System.Convert.ToInt32(smtpServerPort);

                System.Net.Mail.SmtpClient smtp = new SmtpClient(smtpServer, port);

                MailAddress from = new MailAddress(smtpUser, "Mail Admin");
                MailAddress to = new MailAddress(pstrTo, Name);
                mailMsg = new MailMessage(from, to);
                mailMsg.Subject = pstrSubject;
                mailMsg.Body = strMessage;

                //add BCC if we have it
                if (!String.IsNullOrEmpty(bcc))
                {
                    mailMsg.Bcc.Add(bcc);
                }

                //attach file if we have one...
                if (!String.IsNullOrEmpty(attachFilePath))
                {
                    mailMsg.Attachments.Add(new Attachment(attachFilePath));
                }

                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.EnableSsl = true;
                smtp.Timeout = 5000;
                smtp.Send(mailMsg);
                return true;
            }
            catch (Exception x)
            {
                throw x;
            }
            finally
            {
                if (mailMsg != null)
                    mailMsg.Dispose();
            }
        }

 

 

NOTES:

I assumed port 25 was used.  This was for simplicity only, your mail server may be different.