收藏本站 企业邮箱资讯集合地

阿里云企业邮箱SMTP邮件投递代码之CSharp调用示例

本文介绍使用CSharp通过SMTP协议发信。

阿里邮箱配置

SMTP服务器地址:smtp.qiye.aliyun.com或smtp.mxhichina.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("发信地址", "昵称");

                // 显示的发信地址,如果需要去掉注释

                //mailMsg.Sender = new MailAddress("显示的发信地址");

                mailMsg.To.Add(new MailAddress("目标收信地址"));

                //mailMsg.CC.Add("抄送人地址");

                //mailMsg.Bcc.Add("密送人地址");

                //可选,设置回信地址 

                mailMsg.ReplyToList.Add("***");

                // 邮件主题

                mailMsg.Subject = "邮件主题C#测试";

                // 邮件正文内容

                string text = "欢迎使用阿里邮箱";

                string html = @"欢迎使用<a href=""https://qiye.aliyun.com"">阿里邮箱</a>";

                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));

                mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));


                // 添加附件

                string file = "D:\\1.txt";

                Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);

                mailMsg.Attachments.Add(data);

                //阿里邮箱的SMT地址和端口

                SmtpClient smtpClient = new SmtpClient("smtp.qiye.aliyun.com", 25);


                //C#官方文档介绍说明不支持隐式TLS方式,即465端口,需要使用25或者80端口(ECS不支持25端口),另外需增加一行 smtpClient.EnableSsl = true; 故使用SMTP加密方式需要修改如下:

                //SmtpClient smtpClient = new SmtpClient("smtp.qiye.aliyun.com", 80);

                //smtpClient.EnableSsl = true;


                // 使用SMTP用户名和密码进行验证,如果开启三方客户端安全密码请使用新生成的密码

                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("发信地址", "密码");

                smtpClient.Credentials = credentials;

                smtpClient.Send(mailMsg);

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.ToString());

            }

        }

   }


}


相关文章

13812657908