C# code example for SMTP

更新时间:
复制 MD 格式

Send email through Direct Mail using C# with either the built-in System.Net.Mail library or the modern MailKit library.

Important

Test this code thoroughly before using it in a production environment.

Direct Mail supports two C# approaches for SMTP. Use MailKit for new projects — Microsoft no longer recommends System.Net.Mail for new development.

Library

Ports

Encryption

When to use

MailKit

465 (SSL), 80 (none)

SSL (port 465) or none (port 80)

New development — recommended

System.Net.Mail

25, 80

STARTTLS via EnableSsl

Existing code only

System.Net.Mail example

Microsoft has deprecated SmtpClient for new development. If you are starting a new project, use the MailKit example instead.

This example uses System.Net.Mail.SmtpClient to send an email with an attachment over port 25. To use TLS encryption, switch to port 80 and enable SSL as shown in the commented lines.

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("The sender address created in the console", "Nickname");
                mailMsg.Sender = new MailAddress("The displayed sender address");
                mailMsg.To.Add(new MailAddress("The destination address"));
                //mailMsg.CC.Add("CC address");
                //mailMsg.Bcc.Add("BCC address");
                // Optional. Set the reply-to address. 
                mailMsg.ReplyToList.Add("***");
                // The email subject.
                mailMsg.Subject = "C# test for email subject";
                // The email body.
                string text = "Welcome to Alibaba Cloud Direct Mail";
                string html = @"Welcome to <a href=""https://dm.console.aliyun.com"">Direct Mail</a>";
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));

                // Add an attachment.
                string file = "D:\\1.txt";
                Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
                mailMsg.Attachments.Add(data);
                // The SMTP address and port for Direct Mail.
                SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 25);

                // The official C# documentation states that implicit TLS (port 465) is not supported. Use port 25 or 80. Note that ECS does not support port 25. You must also add the line smtpClient.EnableSsl = true. To use SMTP encryption, modify the code as follows:
                //SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 80);
                //smtpClient.EnableSsl = true;

                // Authenticate using the SMTP username and password.
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("The sender address created in the console", "The SMTP password set in the console");
                smtpClient.Credentials = credentials;
                smtpClient.Send(mailMsg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
   }

}

Key points:

  • Sender address: use the sender address you created in the Direct Mail console.

  • SMTP credentials: authenticate with the sender address as the username and the SMTP password you set in the console.

  • Port 25 vs. port 80: System.Net.Mail does not support implicit TLS (port 465). Use port 25 for unencrypted connections or port 80 with smtpClient.EnableSsl = true for STARTTLS. Alibaba Cloud ECS blocks port 25 — use port 80 instead.

FAQ

Error message: 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)

Check that the server address and port are correct. Do not use port 465 with System.Net.Mail — use port 80 with SSL enabled instead:

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

smtpClient.EnableSsl = true;

MailKit example

MailKit is a cross-platform .NET library for SMTP, IMAP, and POP3. Install it via NuGet before running the example.

image

image

This example connects to Direct Mail over port 465 with SSL and sends an email with two attachments.

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

public class EmailSender
{
    public static void SendEmail()
    {
        try
        {
            // Create an email message.
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("Sender", "sender@example.com"));
            message.To.Add(new MailboxAddress("Recipient", "recipient@example.com"));
            message.Subject = "Test email";

            // Body section.
            var bodyBuilder = new BodyBuilder();
            bodyBuilder.TextBody = "This is a test email.";

            // Add attachment 1.
            bodyBuilder.Attachments.Add("C:\\Users\\Downloads\\111.txt");
            // Add attachment 2.
            bodyBuilder.Attachments.Add("C:\\Users\\Downloads\\222.txt");

            // Combine the content.
            message.Body = bodyBuilder.ToMessageBody();

            // Use port 465 with SSL.
            using (var client = new SmtpClient())
            {
                client.Connect("smtpdm.aliyun.com", 465, true); // Encrypted. The third parameter `useSsl` is set to true.
                //client.Connect("smtpdm.aliyun.com", 80, false); // Not encrypted. The third parameter `useSsl` is set to false.
                client.Authenticate("sender@example.com", "xxxxxxxx");
                client.Send(message);
                client.Disconnect(true);
                Console.WriteLine("Email sent successfully!");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // Select the sending method.
        EmailSender.SendEmail();
    }
}

Key points:

  • Port and encryption: client.Connect takes the host, port, and a boolean useSsl. Pass true on port 465 for SSL; pass false on port 80 for an unencrypted connection.

  • Credentials: pass your sender address as the username and your SMTP password to client.Authenticate.

  • Disconnect: call client.Disconnect(true) to send a QUIT command before closing the connection.

Result

image