C# SMTP Helper

SMTP (Simple Mail Transfer Protocol) is an internet standard for email supported by almost all email servers. Connecting with SMTP allows you to send emails from a remote server.[1]

Usage

First, initialize the SmtpHelper class with set the values for the following:

  • Host
  • Sender
  • SenderDisplayName (optional)
  • Password
  • Attachments (optional, an array of strings to file path).

Next, you can chain the following functions:

  • SetSubject(string)
  • SetBody(message, isHtml: Boolean)
  • AddRecipient(email, optionalDisplayName)
  • AddCc(email, optionalDisplayName)
  • AddBcc(email, optionalDisplayName)
  • AddReplyTo(email, optionalDisplayName)
  • Send()

Example

var token = ForgetPasswordTokenHelper.GenerateToken(secret);
var email = "earl@earlpeter.com";
var message = $"Hello, Earl Peter JG!\n\n" +
		"You have requested to reset your password. Use the following link:\n" +
		$"https://test.earlpeter.com /login/reset-password?user={HttpUtility.UrlEncode(email)}&token={HttpUtility.UrlEncode(token)} \n\n" +
		"The link is valid for 1 hour.\n\n" +
		"If you did not request a password change, you can ignore this email.\n\n" +
		"Thank you!";
var smtpHelper = new SmtpHelper {
		Host = "smtp.earlpeter.com",
		Sender = "no-reply@earlpeter.com",
		SenderDisplayName = "Earl Peter JG",
		Password = "changeme"
};
smtpHelper
		.SetSubject("SMTP Test")
		.SetBody(message, isHtml: false)
		.AddRecipient(email, "Sam Ruben")
		.Send();

[1] Microsoft. (2021). SMTP – Connectors. Microsoft.com. https://docs.microsoft.com/en-us/connectors/smtp/