SMTP 之 CSharp 调用示例

通过 SMTP 协议发送带附件的邮件示例

using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MailMessage mailMsg = new MailMessage();
                mailMsg.From = new MailAddress("控制台创建的发信地址", "昵称");
                mailMsg.Sender = new MailAddress("显示的发信地址");
                mailMsg.To.Add(new MailAddress("目标地址"));
                //mailMsg.CC.Add("抄送人地址");
                //mailMsg.Bcc.Add("密送人地址");
                //可选,设置回信地址 
                mailMsg.ReplyToList.Add("***");
                // 邮件主题
                mailMsg.Subject = "邮件主题C#测试";
                // 邮件正文内容
                string text = "欢迎使用阿里云邮件推送";
                string html = @"欢迎使用<a href=""https://dm.console.aliyun.com"">邮件推送</a>";
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

                // 添加附件
                string file = "D:\\1.txt";
                Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
                mailMsg.Attachments.Add(data);
                //邮件推送的SMTP地址和端口
                SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 25);

                //C#官方文档介绍说明不支持隐式TLS方式,即465端口,需要使用25或者80端口(ECS不支持25端口),另外需增加一行 smtpClient.EnableSsl = true; 故使用SMTP加密方式需要修改如下:
                //SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 80);
                //smtpClient.EnableSsl = true;

                // 使用SMTP用户名和密码进行验证
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("控制台创建的发信地址", "控制台设置的SMTP密码");
                smtpClient.Credentials = credentials;
                smtpClient.Send(mailMsg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
   }

}