All Products
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)
                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 
                // Subject
                mailMsg.Subject = "SubjectC#Test";
                // Body content
                string text = "Welcome to Alibaba Cloud DirectMail";
                string html = @"Welcome to <a href="""">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);
                //DirectMail SMTP address and port
                SmtpClient smtpClient = new SmtpClient("", 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;
            catch (Exception ex)