Advertisement
Guest User

Gmail SMTP

a guest
Nov 22nd, 2024
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.98 KB | None | 0 0
  1. public record MailSettings(string Username, string Password, int Port, string FromEmail, string Host);
  2.  
  3. public class MailService(MailSettings mailConfig)  
  4. {
  5.     public async Task SendEmailAsync(string toEmail, string subject, string htmlBody)
  6.     {
  7.         using SmtpClient client = new(mailConfig.Host, mailConfig.Port);
  8.         using MailMessage mail = new(mailConfig.FromEmail, toEmail, subject, htmlBody);
  9.  
  10.         client.Credentials = new NetworkCredential(mailConfig.Username, mailConfig.Password);
  11.         client.EnableSsl = true;
  12.         mail.IsBodyHtml = true;
  13.         await client.SendMailAsync(mail);
  14.     }
  15. }
  16.  
  17. MailService mailService = new(
  18.     mailConfig: new MailSettings(
  19.         Username: "YOUR_EMAIL",
  20.         Password: "APP_ID_PASSWORD",
  21.         Port: 587,
  22.         FromEmail: "YOUR_EMAIL",
  23.         Host: "smtp.gmail.com"
  24.     )
  25. );
  26.  
  27. await mailService.SendEmailAsync(
  28.     toEmail: Email,
  29.     subject: "Subject Line",
  30.     htmlBody: "Email Body in HTML"
  31. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement