1.命名空间 using System.Net.Mail;

2.创建一个MailMessage类的对象

  1. MailMessage mail = new MailMessage();
  1. MailMessage mail = new MailMessage();

3.设置邮件的各种属性

//设置邮件的标题

mail.Subject = "测试邮件";

//设置邮件的发件人

mail.From = new MailAddress("leowangzi@163.com","Leo");

//设置邮件的收件人

mail.To.Add(new MailAddress("lichao.wang@amusegroup.com","Daniel"));

//设置邮件的抄送人

mail.CC.Add(new MailAddress("nick.yin@amusegroup.com","Nick"));

//设置邮件的内容

mail.Body = "就是测试用";

  1. mail.Body = "就是测试用";

//设置邮件的格式

  1. //设置邮件的格式
  1. mail.BodyEncoding = System.Text.Encoding.UTF8;
  1. mail.IsBodyHtml = true;

////设置邮件的发送级别

  1. ////设置邮件的发送级别
  1. mail.Priority = MailPriority.Normal;

mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;

  1. mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;

SmtpClient client = new SmtpClient();

  1. SmtpClient client = new SmtpClient();

//设置用于 SMTP 事务的主机的名称,填IP地址也可以了

  1. //设置用于 SMTP 事务的主机的名称,填IP地址也可以了

client.Host = "smtp.163.com";

  1. client.Host = "smtp.163.com";

//设置用于 SMTP 事务的端口,默认的是 25

  1. //设置用于 SMTP 事务的端口,默认的是 25

//client.Port = 25;

  1. //client.Port = 25;

client.UseDefaultCredentials = false;

  1. client.UseDefaultCredentials = false;

client.Credentials = new System.Net.NetworkCredential("leowangzi@163.com","*******");

  1. client.Credentials = new System.Net.NetworkCredential("leowangzi@163.com", "*******");

client.DeliveryMethod = SmtpDeliveryMethod.Network;

  1. client.DeliveryMethod = SmtpDeliveryMethod.Network;

//都定义完了,正式发送了!            client.Send(mail);

  1. //都定义完了,正式发送了!            client.Send(mail);

4.当需要发送多人时

string displayName = "";

  1. string displayName = "";
  1. string[] mailNames = (txtMailTo.Text + ";").Split(';');
  1. foreach (string name in mailNames)
  1. {    if (name != string.Empty)
  1. {         mail.To.Add(new MailAddress(name , displayName));   }
  1. }

5.当需要发送附件时

  1. //设置邮件的附件,将在客户端选择的附件先上传到服务器保存一个,然后加入到mail中

string fileName = txtUpFile.PostedFile.FileName.Trim();

  1. string fileName = txtUpFile.PostedFile.FileName.Trim();

fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1);

  1. fileName = "D:/UpFile/" + fileName.Substring(fileName.LastIndexOf("/") + 1);

txtUpFile.PostedFile.SaveAs(fileName);

  1. txtUpFile.PostedFile.SaveAs(fileName);

// 将文件保存至服务器mail.

  1. // 将文件保存至服务器mail.

Attachments.Add(new Attachment(fileName));

  1. Attachments.Add(new Attachment(fileName));

6.也可以这么发送附件

//Attachment

string strFilePath = @"C:\test.jpg";

Attachment at = new Attachment(strFilePath);

at.Name = System.IO.Path.GetFileName(strFilePath);

at.NameEncoding = System.Text.Encoding.GetEncoding("gb2312");

at.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;

at.ContentDisposition.Inline = true;

at.ContentDisposition.DispositionType = System.Net.Mime.DispositionTypeNames.Inline;

string cid = at.ContentId;

mail.Attachments.Add(at);

  1. //Attachment
  2. string strFilePath = @"C:\test.jpg";
  3. Attachment at = new Attachment(strFilePath);
  4. at.Name = System.IO.Path.GetFileName(strFilePath);
  5. at.NameEncoding = System.Text.Encoding.GetEncoding("gb2312");
  6. at.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
  7. at.ContentDisposition.Inline = true;
  8. at.ContentDisposition.DispositionType = System.Net.Mime.DispositionTypeNames.Inline;
  9. string cid = at.ContentId;
  10. mail.Attachments.Add(at);

7.另外的说明

●MailMessage类,用于构造电子邮件
●MailAttachment类,用于构造电子邮件附件
●SmtpMail类,用于发送电子邮件及其附件
1、MailMessage类构造电子邮件
此类主要有以下属性和方法
★From     发件人的地址
★To       以分号分隔的收件人的地址列表
★Cc       以分号隔开的抄送的收件人的邮件地址列表
★Subject  电子邮件的主题
★Body     电子邮件的正文
★BodyFormat 电子邮件的正文内容类型,由MailFormat枚举值指定,MailFormat.Text或MailFormat.Html
★Attachments 电子邮件附件集合
★Priority  电子邮件的优先级,由MailPriority枚举值指定,可以是MailPriority.Low ,MailPriority.Normal或MailPriority.High三者之一
2、Attachment用来构造电子邮件附件.用此类构造了电子邮件附件然后添加到MailMessage对象的Attachments集合即可
3、使用SmtpMail类发送电子邮件,可以通过系统本身的SMTP邮件服务或者其它SMTP服务器来发送,发送电子邮件首先需要设置SmtpMail类的SmtpServer属性,然后使用Send方法发送就可以了

8.关于HTML

  1. HTML格式邮件中,嵌入图片资源
  2. 要求收到后,发送回执给你
  3. 如果邮件发送失败, 发送错误通知邮件给你
  4. 支持 HTML/plain text 双格式的邮件, 收件端可以自行切换
  5. 自定义邮件头
  6. 异步发送, 支持取消发送
  7. 邮件回执, 支持 Lotus Notes 的 domino server
SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Host = "smtp.163.com";
smtp.Credentials = new NetworkCredential("三角猫@163.com", "这是密码"); MailMessage mm = new MailMessage();
mm.From = new MailAddress("三角猫@163.com", "三角猫", Encoding.GetEncoding(936));
mm.To.Add("三角猫@gmail.com"); mm.SubjectEncoding = Encoding.GetEncoding(936);
mm.Subject = "三角猫发的测试邮件,呵呵"; mm.BodyEncoding = Encoding.GetEncoding(936); ////普通文本邮件内容,如果对方的收件客户端不支持HTML,这是必需的
string plainTextBody = "如果你邮件客户端不支持HTML格式,或者你切换到“普通文本”视图,将看到此内容";
mm.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(plainTextBody, null, "text/plain")); ////HTML格式邮件的内容
string htmlBodyContent = "如果你的看到<b>这个</b>, 说明你是在以 <span style=\"color:red\">HTML</span> 格式查看邮件<br><br>";
htmlBodyContent += "<a href=\"http://www.zu14.cn/\">真有意思网</a> <img src=\"cid:weblogo\">"; //注意此处嵌入的图片资源
AlternateView htmlBody = AlternateView.CreateAlternateViewFromString(htmlBodyContent, null, "text/html"); ////处理嵌入图片
LinkedResource lrImage = new LinkedResource(@"d:\blogo.gif", "image/gif");
lrImage.ContentId = "weblogo"; //此处的ContentId 对应 htmlBodyContent 内容中的 cid: ,如果设置不正确,请不会显示图片
htmlBody.LinkedResources.Add(lrImage); mm.AlternateViews.Add(htmlBody); ////要求回执的标志
mm.Headers.Add("Disposition-Notification-To", "接收回执的邮箱@163.com"); ////自定义邮件头
mm.Headers.Add("X-Website", "http://www.zu14.cn/"); ////针对 LOTUS DOMINO SERVER,插入回执头
mm.Headers.Add("ReturnReceipt", "1"); mm.Priority = MailPriority.Normal; //优先级
mm.ReplyTo = new MailAddress("回复邮件的接收地址@yahoo.com.cn", "我自己", Encoding.GetEncoding(936)); ////如果发送失败,SMTP 服务器将发送 失败邮件告诉我
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure; ////异步发送完成时的处理事件
smtp.SendCompleted += new SendCompletedEventHandler(smtp_SendCompleted); ////开始异步发送
smtp.SendAsync(mm, null);
void smtp_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("发送被取消");
}
else
{
if (e.Error == null)
{
MessageBox.Show("发送成功");
}
else
{
MessageBox.Show("发送失败: " + e.Error.Message);
}
}
}

一些关于C#发送邮件的代码的更多相关文章

  1. 使用C#模拟Outlook发送邮件,代码编译报错

    添加OutLook API using OutLook = Microsoft.Office.Interop.Outlook; 发送邮件方法 public void SendEmail() { Out ...

  2. phpmailer使用qq邮箱、163邮箱成功发送邮件实例代码

    以前使用qq邮箱.163服务器发送邮件,帐号直接使用密码,现在不行了,得使用授权码,简单记录下 1.首先开通POP3/SMTP服务,qq邮箱——帐号——设置,找到POP3/SMTP点开启,输入短信会有 ...

  3. thinkphp5发送邮件(实例代码 非常适合新手)

    第一步:在(https://pan.baidu.com/s/1Fq6lONHlft5D6jvOnNwtoA)下载 phpmailer.rar 解压 然后把文件放入 vendor目录下 第二步:在 ap ...

  4. C# 发送邮件实例代码

    1.构造附件 static List<Attachment> BuildAttachments(List<EmailFile> files) { ) { return null ...

  5. MVC的验证(模型注解和非侵入式脚本的结合使用) .Net中初探Redis .net通过代码发送邮件 Log4net (Log for .net) 使用GDI技术创建ASP.NET验证码 Razor模板引擎 (RazorEngine) .Net程序员应该掌握的正则表达式

    MVC的验证(模型注解和非侵入式脚本的结合使用)   @HtmlHrlper方式创建的标签,会自动生成一些属性,其中一些属性就是关于验证 如图示例: 模型注解 通过模型注解后,MVC的验证,包括前台客 ...

  6. flask使用blinker信号机制解耦业务代码解决ImportError: cannot import name 'app',以异步发送邮件为例

    百度了大半天,不知道怎么搞,直到学习了blinker才想到解决办法,因为之前写java都是文件分开的, 所以发送邮件业务代码也放到view里面,但是异步线程需要使用app,蛋疼的是其他模块不能从app ...

  7. python2.7发送邮件失败之——代码问题

    使用python2.7发送邮件,代码如下: from email.header import Headerfrom email.mime.text import MIMETextimport smtp ...

  8. python发送邮件及附件

    今天给大伙说说python发送邮件,官方的多余的话自己去百度好了,还有一大堆文档说实话不到万不得已的时候一般人都不会去看,回归主题: 本人是mac如果没有按照依赖模块的请按照下面的截图安装 导入模块如 ...

  9. .Net中使用SendGrid Web Api发送邮件(附源码)

    SendGrid是一个第三方的解决邮件发送服务的提供商,在国外使用的比较普遍.国内类似的服务是SendCloud.SendGrid提供的发送邮件方式主要是两种, 一种是SMTP API, 一种是Web ...

随机推荐

  1. 基于函数计算 + TensorFlow 的 Serverless AI 推理

    前言概述 本文介绍了使用函数计算部署深度学习 AI 推理的最佳实践, 其中包括使用 FUN 工具一键部署安装第三方依赖.一键部署.本地调试以及压测评估, 全方位展现函数计算的开发敏捷特性.自动弹性伸缩 ...

  2. SQL Server死锁问题:事务(进程 ID x)与另一个进程被死锁在 锁 | 通信缓冲区资源上并且已被选作死锁牺牲品。请重新运行该事务。

    ### The error occurred while setting parameters### SQL: update ERP_SCjh_zzc_pl set IF_TONGBU=1 where ...

  3. POJ 3764 The xor-longest Path ( 字典树求异或最值 && 异或自反性质 && 好题好思想)

    题意 : 给出一颗无向边构成的树,每一条边都有一个边权,叫你选出一条路,使得此路所有的边的异或值最大. 分析 : 暴力是不可能暴力的,这辈子不可能暴力,那么来冷静分析一下如何去做.假设现在答案的异或值 ...

  4. 软件安装——internal error2503/2502

    安装新的软件后先报internal error 2503,随后报internal error 2502.就是不让我装新的软件,提示说发生严重错误,然后安装失败. Solution for intern ...

  5. HDU 4348 SPOJ 11470 To the moon

    Vjudge题面 Time limit 2000 ms Memory limit 65536 kB OS Windows Source 2012 Multi-University Training C ...

  6. 使用visual studio配置和运行《opengl圣经》的第一个案例

    对vc++新手来说,想把opengl圣经里的教学案例运行起来还真不是一件容易的事情,而且并没有完整的操作流程教学,这里就总结一下吧: 先安装cmake,用于生成vs的工程文件,安装过程中选中“将目录添 ...

  7. 封装类和非封装类比较相同不int和Integer

    A.所有和int(非封装类比较的,只要数值相同就行) B.io3由valueof弄出来的,所以和io1相同 C.io4是new出来的,所以地址不一样,就不相同 D.和A相同

  8. zabbix主动、被动TCP连接过程

    zabbix主动.被动TCP连接过程 https://blog.csdn.net/u010668387/article/details/79460183

  9. linux socket 缓存: core rmem_default rmem_max

    https://blog.csdn.net/penzchan/article/details/41682411

  10. 裸BFS题若干

    1poj 3278 http://poj.org/problem?id=3278 #include<math.h> #include<algorithm> #include&l ...