Last active
December 23, 2023 00:52
-
-
Save pranavq212/1cbecac15abb229d40f1ad0765aa4dce to your computer and use it in GitHub Desktop.
Send mail via SMTP c#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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