using System;
using System.Net;
using System.Net.Mail;
namespace SendGridMail.Transport
{
///
/// Transport class for delivering messages via SMTP
///
public class SMTP : ITransport
{
///
/// SendGrid's host name
///
public const String SmtpServer = "smtp.sendgrid.net";
///
/// Port for Simple Mail Transfer Protocol
///
public const Int32 Port = 25;
///
/// Port for Secure SMTP
///
public const Int32 SslPort = 465;
///
/// Port for TLS (currently not supported)
///
public const Int32 TlsPort = 571;
///
/// Client used to deliver SMTP message
///
private readonly ISmtpClient _client;
///
/// Transport created to deliver messages to SendGrid using SMTP
///
/// SMTP client we are wrapping
/// Sendgrid user credentials
/// MTA recieving this message. By default, sent through SendGrid.
/// SMTP port 25 is the default. Port 465 can be used for Secure SMTP.
private SMTP(ISmtpClient client, NetworkCredential credentials, string host = SmtpServer, int port = Port)
{
_client = client;
switch (port)
{
case Port:
break;
case SslPort:
_client.EnableSsl = true;
break;
case TlsPort:
throw new NotSupportedException("TLS not supported");
}
}
///
/// Deliver an email using SMTP protocol
///
///
public void Deliver(ISendGrid message)
{
var mime = message.CreateMimeMessage();
_client.Send(mime);
}
///
/// Transport created to deliver messages to SendGrid using SMTP
///
/// Sendgrid user credentials
/// MTA recieving this message. By default, sent through SendGrid.
/// SMTP port 25 is the default. Port 465 can be used for Secure SMTP.
public static SMTP GenerateInstance(NetworkCredential credentials, String host = SmtpServer, Int32 port = Port)
{
var client = new SmtpWrapper(host, port, credentials, SmtpDeliveryMethod.Network);
return new SMTP(client, credentials, host, port);
}
///
/// For Unit Testing Only!
///
///
///
///
///
///
internal static SMTP GenerateInstance(ISmtpClient client, NetworkCredential credentials, String host = SmtpServer, Int32 port = Port)
{
return new SMTP(client, credentials, host, port);
}
///
/// Interface to allow testing
///
internal interface ISmtpClient
{
bool EnableSsl { get; set; }
void Send(MailMessage mime);
}
///
/// Implementation of SmtpClient wrapper, separated to allow dependency injection
///
internal class SmtpWrapper : ISmtpClient
{
private readonly SmtpClient _client;
public bool EnableSsl
{
get
{
return _client.EnableSsl;
}
set
{
_client.EnableSsl = value;
}
}
public SmtpWrapper(String host, Int32 port, NetworkCredential credentials, SmtpDeliveryMethod deliveryMethod)
{
_client = new SmtpClient(host, port) { Credentials = credentials, DeliveryMethod = deliveryMethod };
}
public void Send(MailMessage mime)
{
_client.Send(mime);
}
}
}
}