SMTP 之 CSharp 调用示例

重要

风险提示:用于生产环境之前请务必先做好测试。

System.Net.Mail示例

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());
            }
        }
   }

}

常见问题

报错提示:The connection was closed

System.Net.Mail.SmtpException: Failure sending mail.
 ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed.
 at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
 at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
 at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
 at System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port)
 at System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port)
 at System.Net.Mail.SmtpClient.Send(MailMessage message)
 --- End of inner exception stack trace ---
 at System.Net.Mail.SmtpClient.Send(MailMessage message)
 at ConsoleApp.Program.Main(String[] args)

请确认服务器地址和端口正确,加密方式连接时要使用正确的连接配置。

该示例不要使用465端口,用80代替。

SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 80);

smtpClient.EnableSsl = true;

MailKit示例

通过NuGet安装Mailkit。

image

image

using MailKit.Net.Smtp;
using MimeKit;
using System;
using System.IO;

public class EmailSender
{
    public static void SendEmail()
    {
        try
        {
            // 创建邮件消息
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("发件人", "sender@example.com"));
            message.To.Add(new MailboxAddress("收件人", "recipient@example.com"));
            message.Subject = "测试邮件";

            // 正文部分
            var bodyBuilder = new BodyBuilder();
            bodyBuilder.TextBody = "这是一封测试邮件。";

            // 添加附件1
            bodyBuilder.Attachments.Add("C:\\Users\\Downloads\\111.txt");
            // 添加附件2
            bodyBuilder.Attachments.Add("C:\\Users\\Downloads\\222.txt");

            // 组合内容
            message.Body = bodyBuilder.ToMessageBody();

            // 使用 465端口 + SSL
            using (var client = new SmtpClient())
            {
                client.Connect("smtpdm.aliyun.com", 465, true); // 加密,第三个参数 `useSsl` 设为 true
                //client.Connect("smtpdm.aliyun.com", 80, false); // 不加密,第三个参数 `useSsl` 设为 false
                client.Authenticate("sender@example.com", "xxxxxxxx");
                client.Send(message);
                client.Disconnect(true);
                Console.WriteLine("邮件发送成功!");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"错误: {ex.Message}");
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // 选择发送方式
        EmailSender.SendEmail();
    }
}

效果展示

image