SMTP 之 CSharp 調(diào)用示例
更新時(shí)間:
通過(guò) SMTP 協(xié)議發(fā)送帶附件的郵件示例
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("控制臺(tái)創(chuàng)建的發(fā)信地址", "昵稱(chēng)");
mailMsg.Sender = new MailAddress("顯示的發(fā)信地址");
mailMsg.To.Add(new MailAddress("目標(biāo)地址"));
//mailMsg.CC.Add("抄送人地址");
//mailMsg.Bcc.Add("密送人地址");
//可選,設(shè)置回信地址
mailMsg.ReplyToList.Add("***");
// 郵件主題
mailMsg.Subject = "郵件主題C#測(cè)試";
// 郵件正文內(nèi)容
string text = "歡迎使用阿里云郵件推送";
string html = @"歡迎使用<a href=""https://dm.console.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);
//郵件推送的SMTP地址和端口
SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 25);
//C#官方文檔介紹說(shuō)明不支持隱式TLS方式,即465端口,需要使用25或者80端口(ECS不支持25端口),另外需增加一行 smtpClient.EnableSsl = true; 故使用SMTP加密方式需要修改如下:
//SmtpClient smtpClient = new SmtpClient("smtpdm.aliyun.com", 80);
//smtpClient.EnableSsl = true;
// 使用SMTP用戶(hù)名和密碼進(jìn)行驗(yàn)證
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("控制臺(tái)創(chuàng)建的發(fā)信地址", "控制臺(tái)設(shè)置的SMTP密碼");
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
文檔內(nèi)容是否對(duì)您有幫助?