Use the following C# sample code to send emails over SMTP using Alibaba Mail.
Alibaba Mail configuration
Prerequisites
Before you begin, ensure that you have:
An Alibaba Mail account with SMTP access enabled
The sender email address configured in your Alibaba Mail account
Your account password or, if a security password for third-party clients is enabled, the generated security password
SMTP connection parameters
|
Parameter |
Value |
|
SMTP server |
smtp.sg.aliyun.com |
|
Port |
25 (plain), or 25 with |
|
Username |
Your sender email address |
|
Password |
Your account password, or the security password for third-party clients if enabled |
Note:System.Net.Mail.SmtpClientdoes not support implicit TLS (port 465), which wraps the entire connection in TLS before any SMTP handshake. Port 25 withEnableSsl = trueuses STARTTLS, which upgrades a plain connection to encrypted after the handshake begins. Port 25 is disabled by default on ECS instances.
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);
// Connect to the Alibaba Mail SMTP server on port 25 (plain).
SmtpClient smtpClient = new SmtpClient("smtp.sg.aliyun.com", 25);
// To send over an encrypted connection using STARTTLS, enable SSL on port 25:
//SmtpClient smtpClient = new SmtpClient("smtp.sg.aliyun.com", 25);
//smtpClient.EnableSsl = true;
// Authenticate with your sender address and password.
// If a security password for third-party clients is enabled, use that generated password here.
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("Sender address", "Password");
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}