Skip to content

Instantly share code, notes, and snippets.

@SafeerH
Created May 20, 2015 05:48
Show Gist options
  • Save SafeerH/a1d226847374079e2ddb to your computer and use it in GitHub Desktop.
Save SafeerH/a1d226847374079e2ddb to your computer and use it in GitHub Desktop.
Simple SMTP Email Service [for ASP.NET 5 (vNext)]
This is a simple SMTP email sender (service) [for ASP.NET 5 (vNext)].
{
"Data": {
"EmailSettings": {
"Server": "smtp.gmail.com",
"EnableSsl": true,
"Port": 587,
"UserName": "someone@gmail.com",
"Password": "someP@55word",
"DisplayName": "John Doe"
}
}
}
using System;
using System.Net.Mail;
using Microsoft.Framework.ConfigurationModel;
namespace Mzmsh.SimpleSmtpEmail
{
public class EmailService
{
private readonly IConfiguration _config;
private readonly EmailSettings _settings;
public EmailService(IConfiguration config)
{
_config = config;
_settings = new EmailSettings()
{
Server = _config["Data:EmailSettings:Server"],
EnableSsl = Convert.ToBoolean(_config["Data:EmailSettings:EnableSsl"]),
Port = Convert.ToInt16(_config["Data:EmailSettings:Port"]),
UserName = _config["Data:EmailSettings:UserName"],
Password = _config["Data:EmailSettings:Password"],
DisplayName = _config["Data:EmailSettings:DisplayName"],
};
}
public void SendEmail(string toEmailAddress, string subject, string body)
{
SendEmail(new[] {toEmailAddress}, subject, body);
}
public void SendEmail(string[] toEmailAddresses, string subject, string body)
{
MailMessage message = new MailMessage();
MailAddress sender = new MailAddress(_settings.UserName, _settings.DisplayName);
SmtpClient smtp = new SmtpClient()
{
Host = _settings.Server,
Port = _settings.Port,
EnableSsl = _settings.EnableSsl,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(_settings.UserName, _settings.Password),
DeliveryMethod = SmtpDeliveryMethod.Network
};
message.From = sender;
foreach (var strEmail in toEmailAddresses)
message.To.Add(new MailAddress(strEmail.Trim()));
message.Subject = subject;
message.Body = body;
message.IsBodyHtml = true;
smtp.Send(message);
}
}
}
namespace Mzmsh.SimpleSmtpEmail
{
public class EmailSettings
{
public string Server { get; set; }
public bool EnableSsl { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string DisplayName { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment