All Products
Search
Document Center

Alibaba Mail:C# sample code for sending emails over SMTP

Last Updated:Aug 26, 2025

This topic provides C# sample code for sending emails over SMTP.

Alibaba Mail configuration

SMTP server address: smtp.sg.aliyun.com

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("Sender address", "Nickname");
                // The displayed sender address. Uncomment if needed.
                //mailMsg.Sender = new MailAddress("Displayed sender address");
                mailMsg.To.Add(new MailAddress("Recipient address"));
                //mailMsg.CC.Add("CC recipient address");
                //mailMsg.Bcc.Add("BCC recipient address");
                // Optional. Set the reply-to address. 
                mailMsg.ReplyToList.Add("***");
                // The email subject.
                mailMsg.Subject = "C# test email subject";
                // The email body.
                string text = "Welcome to Alibaba Mail";
                string html = @"Welcome to <a href=""https://mail.sg.aliyun.com"">Alibaba 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 of Alibaba Mail.
                SmtpClient smtpClient = new SmtpClient("smtp.sg.aliyun.com", 25);

                // C# does not support implicit TLS (port 465). For SMTP encryption, use port 25 and set EnableSsl to true. Note that port 25 is disabled by default on ECS. Modify the code as follows to use encryption:
                //SmtpClient smtpClient = new SmtpClient("smtp.qiye.aliyun.com", 25);
                //smtpClient.EnableSsl = true;

                // Authenticate with the SMTP username and password. If a security password for third-party clients is enabled, use the generated password.
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("Sender address", "Password");
                smtpClient.Credentials = credentials;
                smtpClient.Send(mailMsg);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
   }

}