2025年3月25日 星期二 甲辰(龙)年 月廿四 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

C#发送邮件代码简洁示例(附源码下载)

时间:12-03来源:作者:点击数:29

C#发送邮件,主要使用的是System.Net.Mail命名空间下的方法实现,方法很简单,短短十几行代码即可完成发送,具体代码如下。

  • using System;
  • using System.Collections.Generic;
  • using System.Linq;
  • using System.Net;
  • using System.Net.Mail;
  • using System.Text;
  • using System.Threading.Tasks;
  • namespace SendMessage
  • {
  • public class SendEmail:ISend
  • {
  • public SendResult Send(string[] addresses, string title, string content)
  • {
  • SendResult result = new SendResult();
  • if (addresses.Length == 0)
  • {
  • result.returnstr = "目标地址为空";
  • }
  • else if (string.IsNullOrEmpty(content)) {
  • result.returnstr = "内容为空";
  • }
  • else if (string.IsNullOrEmpty(title)) {
  • result.returnstr = "标题为空";
  • }
  • else
  • {
  • try
  • {
  • MailMessage myMail = new MailMessage();
  • myMail.From = new MailAddress("xxxx@xxxx.cn");
  • foreach (var address in addresses)
  • {
  • myMail.To.Add(new MailAddress(address));
  • }
  • myMail.Subject = title;
  • myMail.SubjectEncoding = Encoding.UTF8;
  • myMail.Body = content;
  • myMail.BodyEncoding = Encoding.UTF8;
  • myMail.IsBodyHtml = false;
  • myMail.Priority = MailPriority.High;
  • //myMail.CC
  • //myMail.Bcc
  • SmtpClient smtpClient = new SmtpClient();
  • smtpClient.Host = "xxxx.xxxx.com";
  • //smtpClient.Port = 23;
  • smtpClient.Credentials = new NetworkCredential("xxxx@xxxx.cn", "yourpassword");
  • smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
  • //smtpClient.EnableSsl = true;
  • smtpClient.Send(myMail);
  • result.status = true;
  • }
  • catch (Exception ex)
  • {
  • result.returnstr = ex.Message;
  • }
  • }
  • return result;
  • }
  • }
  • }

这样邮件就可以发送了。目前主流的一些邮件服务提供商都支持这样发送,但也碰到部分邮箱无法发送,如最近发现新浪的.cn邮箱没法用这种方式发送邮件了,之前是可以的,具体原因也还没空细究。

如果是用自己公司的邮箱一般都没啥问题,亲们可以试试。

源码下载地址:SendEmail.rar

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门