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.



Comments (2) -

Fifania
Fifania
2/19/2015 1:35:56 PM #

It's truly a nice and helpful piece of info. I'm satisfied that you shared this helpful info with us. Please keep us up to date like this. Thanks for sharing.

renovation appartement
renovation appartement
3/20/2015 8:37:49 AM #

Toujours un article passionnant. Merci pour ces partages.

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading