全部产品
Search
文档中心

邮件推送:SMTP 之 CSharp 调用示例

更新时间:Jun 29, 2021

通过 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.From = new MailAddress("控制台创建的发信地址", "昵称");
  16. mailMsg.To.Add(new MailAddress("目标地址"));
  17. //mailMsg.CC.Add("抄送人地址");
  18. //mailMsg.Bcc.Add("密送人地址");
  19. //可选,设置回信地址
  20. mailMsg.ReplyToList.Add("***");
  21. // 邮件主题
  22. mailMsg.Subject = "邮件主题C#测试";
  23. // 邮件正文内容
  24. string text = "欢迎使用阿里云邮件推送";
  25. string html = @"欢迎使用<a href=""https://dm.console.aliyun.com"">邮件推送</a>";
  26. mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
  27. mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
  28. // 添加附件
  29. string file = "D:\\1.txt";
  30. Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
  31. mailMsg.Attachments.Add(data);
  32. //邮件推送的SMTP地址和端口
  33. SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 25);
  34. // 使用SMTP用户名和密码进行验证
  35. System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("控制台创建的发信地址", "控制台设置的SMTP密码");
  36. smtpClient.Credentials = credentials;
  37. smtpClient.Send(mailMsg);
  38. }
  39. catch (Exception ex)
  40. {
  41. Console.WriteLine(ex.ToString());
  42. }
  43. }
  44. }
  45. }