All Products
Search
Document Center

Direct Mail:SMTP - Csharp

Last Updated:Dec 26, 2022

The following example shows how to send an email through SMTP using Csharp.

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.To.Add(new MailAddress("Destination address"));
                //mailMsg.CC.Add("CC address");
                //mailMsg.Bcc.Add("Bcc address");
                //Optional, ReplyTo 
                mailMsg.ReplyToList.Add("***");
                // Subject
                mailMsg.Subject = "SubjectC#Test";
                // Body content
                string text = "Welcome to Alibaba Cloud DirectMail";
                string html = @"Welcome to <a href=""https://dm.console.aliyun.com"">DirectMail</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);
                //DirectMail SMTP address and port
                SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 25);
                //As the official document of C # explains that implicit TLS is not supported, port 465 cannot be used, but port 25 or port 80 can be used (ECS does not support port 25). In addition, a line of code smtpClient.EnableSsl = true needs to be added; Therefore, the SMTP encryption method needs to be modified as follows:
                //SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 80);
                //smtpClient.EnableSsl = true;
                // Verify SMTP user name 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());
            }
        }
   }

}