All Products
Search
Document Center

SMTP - Csharp

Last Updated: Jun 29, 2021

The following example shows how to send an email through SMTP using Csharp.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net.Mail;
  5. using System.Net.Mime;
  6. namespace ConsoleApp
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. try
  13. {
  14. MailMessage mailMsg = new MailMessage();
  15. mailMsg.From = new MailAddress("The sender address created in the console", "Nickname");
  16. mailMsg.To.Add(new MailAddress("Destination address"));
  17. //mailMsg.CC.Add("CC address");
  18. //mailMsg.Bcc.Add("Bcc address");
  19. //Optional,ReplyTo
  20. mailMsg.ReplyToList.Add("***");
  21. // Subject
  22. mailMsg.Subject = "SubjectC#Test";
  23. // Body content
  24. string text = "Welcome to Alibaba Cloud DirectMail";
  25. string html = @"Welcome to <a href=""https://dm.console.aliyun.com"">DirectMail</a>";
  26. mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
  27. mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
  28. // Add an attachment
  29. string file = "D:\\1.txt";
  30. Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
  31. mailMsg.Attachments.Add(data);
  32. //DirectMail SMTP address and port
  33. SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 25);
  34. // Verify SMTP user name and password
  35. System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("The sender address created in the console", "The SMTP password set in the console");
  36. smtpClient.Credentials = credentials;
  37. smtpClient.Send(mailMsg);
  38. }
  39. catch (Exception ex)
  40. {
  41. Console.WriteLine(ex.ToString());
  42. }
  43. }
  44. }
  45. }