Skip to content

Instantly share code, notes, and snippets.

@pranavq212
Last active December 23, 2023 00:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pranavq212/1cbecac15abb229d40f1ad0765aa4dce to your computer and use it in GitHub Desktop.
Save pranavq212/1cbecac15abb229d40f1ad0765aa4dce to your computer and use it in GitHub Desktop.
Send mail via SMTP c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using DomainClasses;
using System.IO;
namespace Helpers
{
/// <summary>
/// Class for Email Methods
/// </summary>
public class EmailHelper
{
/// <summary>
/// Method to Send Mail
/// </summary>
/// <param name="email"></param>
/// <returns>Error message in case of Error</returns>
public static string SendMail(EmailModel email)
{
try
{
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(email.EmailFrom);
mail.To.Add(email.EmailTo);
mail.Subject = email.Subject;
mail.Body = email.Body;
mail.IsBodyHtml=true;
//Way to add attachment
//mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
using (SmtpClient smtp = new SmtpClient(email.SmtpAddress, email.PortNumber))
{
smtp.Credentials = new NetworkCredential(email.EmailFrom, email.Password);
smtp.EnableSsl = email.EnableSSL;
smtp.Send(mail);
}
}
}
catch (SmtpFailedRecipientException exception)
{
Logger.Logger.Error("SMTP error in sending email", exception);
return Utilities.ReturnException(exception);
}
catch (Exception ex)
{
Logger.Logger.Error("Error in Sending Email", ex);
return Utilities.ReturnException(ex);
}
return string.Empty;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment