SMTP-Csharp

Last Updated: Aug 09, 2017

Send a mail with an attachment using SMTP

  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.To.Add(new MailAddress("Destination address"));
  16. mailMsg.From = new MailAddress("The mail address created in the console", "Nickname");
  17. // Subject
  18. mailMsg.Subject = "SubjectC#Test";
  19. // Body content
  20. string text = "Welcome to Alibaba Cloud DirectMail";
  21. string html = @"Welcome to <a href=""https://dm.console.aliyun.com"">DirectMail</a>";
  22. mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
  23. mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
  24. // Add an attachment
  25. string file = "D:\\1.txt";
  26. Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
  27. mailMsg.Attachments.Add(data);
  28. //DirectMail SMTP address and port
  29. SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 25);
  30. // Verify SMTP user name and password
  31. System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("The mail address created in the console", "The SMTP password set in the console");
  32. smtpClient.Credentials = credentials;
  33. smtpClient.Send(mailMsg);
  34. }
  35. catch (Exception ex)
  36. {
  37. Console.WriteLine(ex.ToString());
  38. }
  39. }
  40. }
  41. }
Thank you! We've received your feedback.