Send Email with Sendgrid in C#

Integrate Email API with Sendgrid's SMTP server.

December 27, 2024

public static void SendEmail(string emailstring subjectstring body)
        {
            string SMTP_HOSTNAME = "smtp.sendgrid.net";
            int SMTP_PORT = 587;
            string SMTP_FROM = "no-reply@yourdomain.com";
            string SMTP_USERNAME = "apikey";
            string SMTP_PASSWORD = "smptpassword";
 
            using (SmtpClient client = new SmtpClient(SMTP_HOSTNAMESMTP_PORT))
            {
                MailMessage mailMessage = new MailMessage
                {
                    From = new MailAddress(SMTP_FROM"Display Name"),
                    Subject = subject,
                    Body = body,
                    IsBodyHtml = true  
                };
 
                mailMessage.To.Add(email);
                //mailMessage.To.Add("additional_email");
 
                //mailMessage.CC.Add("cc_email");
 
                //string filePath = "file path";
                //using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                //{
                //    var attachment = new System.Net.Mail.Attachment(fileStream, Path.GetFileName(filePath));
                //    mailMessage.Attachments.Add(attachment);
                //}
 
                client.Credentials = new NetworkCredential(SMTP_USERNAMESMTP_PASSWORD);
                client.EnableSsl = true// or false, depending on your SMTP server
                client.Send(mailMessage);
            }
        }

SendEmail("test@gmail.com""Email Subject""Email Body With HTML");

Post Comments(0)

Leave a reply

Will not be displayed in comment box .

Loading...