全部產品
Search
文件中心

Direct Mail:SMTP 之 CSharp 調用樣本

更新時間:Jul 10, 2025

重要

風險提示:用於生產環境之前請務必先做好測試。

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 = "歡迎使用阿里雲Direct Mail";
                string html = @"歡迎使用<a href=""https://dm.console.alibabacloud.com"">Direct Mail</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);
                //Direct Mail的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