All Products
Search
Document Center

SMTP - Csharp

Last Updated: Apr 07, 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);
                // 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());
            }
        }
   }

}