Use Mailgun over SMTP


Hello folks!
Mailing is an important part of any application. We will see how we can send emails using SMTP MailGun credentials, without exposing the password of the FromMailer.

Prerequisites

  1. SMTP MailGun Credentials for your organization’s domain

Integrating MailGun over SMTP in C#

Note : The from address should be of the domain for which the MailGun credentials have been purchased

public static void SendMailUsingSmtpMainGun(string mailFrom, string mailTo, string subject, string body, List<string> attachments = null)
{
    var smtpClient = new SmtpClient("smtp.mailgun.org")
    {
        Port = 587,
        DeliveryMethod = SmtpDeliveryMethod.Network,
        UseDefaultCredentials = false,
        Credentials = new NetworkCredential("<SmtpUserNameOfMailGun>", "<SmtpPasswordOfMailGun>"]),
        EnableSsl = true,
    };

    MailMessage mail = new MailMessage();
    mail.From = new MailAddress(mailFrom);
    mail.To.Add(mailTo);
    mail.Subject = subject;
    mail.Body = body;

    foreach (string attachment in attachments)
    {
        mail.Attachments.Add(new Attachment(attachment));
    }

    smtpClient.Send(mail);
}

The main advantage of using MailGun is that the sender id’s password isn’t exposed. The ‘From’ address could be any address from the organization domain for which MailGun credentials have been purchased.
Use this and enjoy mailing!!

Leave A Comment

Your email address will not be published. Required fields are marked *