Last active
April 8, 2024 07:52
-
-
Save somedeveloper00/2a1b42f8858f57557faf14e43e2d1bba to your computer and use it in GitHub Desktop.
Send Email with C# standard libraries using SMTP
This file contains hidden or 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
| /// <summary> | |
| /// Send an email from <param name="fromEmail"></param> to <param name="toEmail"></param> and returns the | |
| /// <see cref="Thread"/> that is sending the email, so you can <see cref="Thread.Abort()"/> it later to cancel it. | |
| /// </summary> | |
| /// <param name="fromEmail">Email of the sender</param> | |
| /// <param name="password">Password of the sender</param> | |
| /// <param name="smtpHost">SMTP host address of the server's email service provider. Some common addresses are: | |
| /// <list type="bullet"> | |
| /// <item>Outlook: <c>smtp-mail.outlook.com</c></item> | |
| /// <item>Office 356: <c>smtp.office365.com</c></item> | |
| /// <item>Yahoo Mail: <c>smtp.mail.yahoo.com</c></item> | |
| /// <item>Google Mail: <c>smtp.gmail.com</c></item> | |
| /// </list> | |
| /// Be sure to check your email service provider to ensure the address is correct. If the address is incorrect, the email | |
| /// will not be delivered. | |
| /// </param> | |
| /// <param name="toEmail">Email of the receiver</param> | |
| /// <param name="subject">Subject of the email</param> | |
| /// <param name="body">Body of the email (usually in HTML format)</param> | |
| /// <param name="cancellationToken">token to cancel the email sending thread</param> | |
| /// <returns>The thread of the email posting process</returns> | |
| public static Task SendEmailAsync(string fromEmail, string password, string smtpHost, string[] toEmail, | |
| string subject, string body, CancellationToken cancellationToken) | |
| { | |
| var mailMessage = new MailMessage(fromEmail, string.Join(',', toEmail), subject, body); | |
| var client = new SmtpClient(smtpHost, 587); | |
| client.EnableSsl = true; | |
| client.Credentials = new NetworkCredential(fromEmail, password); | |
| cancellationToken.Register(client.SendAsyncCancel); | |
| return client.SendMailAsync(mailMessage); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment