C#使用Smtp协议发送邮件

使用Smtp协议发送邮件

发送代码,Mail类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;namespace Smtp
{public class Mail{private string sender;/// <summary>/// 发送人/// </summary>public string Sender{get{return sender;}set{sender = value;}}private string senderMail;/// <summary>/// 发送人邮箱/// </summary>public string SenderMail{get{return senderMail;}set{senderMail = value;}}private string senderPw;/// <summary>/// 发送人密码/// </summary>public string SenderPw{get{return senderPw;}set{senderPw = value;}}private string smtpServer;/// <summary>/// smtpServer地址/// </summary>public string SmtpServer{get{return smtpServer;}set{smtpServer = value;}}/// <summary>/// /// </summary>/// <param name="sender">委托发件人</param>/// <param name="sender">委托发件人邮件地址</param>/// <param name="senderPw">密码</param>/// <param name="ewsUrl">smtpServer地址</param>public Mail(string sender, string senderMail, string senderPw, string smtpServer){this.sender = sender;this.senderMail = senderMail;this.senderPw = senderPw;this.smtpServer = smtpServer;}public Mail(){}/// <summary>/// 发送邮件/// </summary>/// <param name="title"></param>/// <param name="body"></param>/// <param name="receiver"></param>public void Send(string title, string body, string[] receiver){SmtpClient _smtpClient = new SmtpClient();_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式_smtpClient.Host = this.smtpServer; ;//指定SMTP服务器_smtpClient.EnableSsl = true;_smtpClient.Port = 587;_smtpClient.Credentials = new System.Net.NetworkCredential(this.sender, this.senderPw);//用户名和密码for (int i = 0; i < receiver.Length; i++){//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);ServicePointManager.ServerCertificateValidationCallback =
delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };MailMessage _mailMessage = new MailMessage(this.senderMail, receiver[i]);_mailMessage.Subject = title;//主题_mailMessage.Body = body;//内容_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码_mailMessage.IsBodyHtml = true;//设置为HTML格式_mailMessage.Priority = MailPriority.High;//优先级//Attachment am = new Attachment(attachment, "attachment");//_mailMessage.Attachments.Add(am);_smtpClient.Send(_mailMessage);}}public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors){//if (sslPolicyErrors == SslPolicyErrors.None)//    return true;//else//    return true;// If there are no errors, then everything went smoothly.if (sslPolicyErrors == SslPolicyErrors.None)return true;// Note: MailKit will always pass the host name string as the `sender` argument.//var host = (string)sender;string host = sender as string;if (host == null){// Handle the case where sender is not a stringConsole.WriteLine("Sender parameter is not a valid string.");return false;}if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0){// This means that there are errors in the certificate chain. You can inspect the chain errors and handle them accordingly.foreach (X509ChainStatus chainStatus in chain.ChainStatus){Console.WriteLine("Certificate chain error: " + chainStatus.StatusInformation);}return false;}if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0){// This means that the remote certificate is unavailable. Notify the user and return false.Console.WriteLine("The SSL certificate was not available for {0}", host);return false;}if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0){// This means that the server's SSL certificate did not match the host name that we are trying to connect to.var certificate2 = certificate as X509Certificate2;var cn = certificate2 != null ? certificate2.GetNameInfo(X509NameType.SimpleName, false) : certificate.Subject;Console.WriteLine("The Common Name for the SSL certificate did not match {0}. Instead, it was {1}.", host, cn);return false;}// The only other errors left are chain errors.Console.WriteLine("The SSL certificate for the server could not be validated for the following reasons:");// The first element's certificate will be the server's SSL certificate (and will match the `certificate` argument)// while the last element in the chain will typically either be the Root Certificate Authority's certificate -or- it// will be a non-authoritative self-signed certificate that the server admin created. foreach (var element in chain.ChainElements){// Each element in the chain will have its own status list. If the status list is empty, it means that the// certificate itself did not contain any errors.if (element.ChainElementStatus.Length == 0)continue;Console.WriteLine("\u2022 {0}", element.Certificate.Subject);foreach (var error in element.ChainElementStatus){// `error.StatusInformation` contains a human-readable error string while `error.Status` is the corresponding enum value.Console.WriteLine("\t\u2022 {0}", error.StatusInformation);}}return false;}/// <summary>/// 发送邮件,带附件/// </summary>/// <param name="title"></param>/// <param name="body"></param>/// <param name="receiver"></param>/// <param name="attachment">附件</param>public void Send(string title, string body, string receiver, System.IO.Stream attachment){SmtpClient _smtpClient = new SmtpClient();_smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式_smtpClient.Host = this.smtpServer; ;//指定SMTP服务器_smtpClient.Credentials = new System.Net.NetworkCredential(this.sender, this.senderPw);//用户名和密码MailMessage _mailMessage = new MailMessage(this.senderMail, receiver);_mailMessage.Subject = title;//主题_mailMessage.Body = body;//内容_mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码_mailMessage.IsBodyHtml = true;//设置为HTML格式_mailMessage.Priority = MailPriority.High;//优先级Attachment am = new Attachment(attachment, "attachment");_mailMessage.Attachments.Add(am);_smtpClient.Send(_mailMessage);}}
}

测试调用,Program类

using System;
using System.Collections.Generic;
using System.Text;namespace SendMail
{class Program{static void Main(string[] args){Smtp.Mail mail = new Smtp.Mail();mail.Sender = "Test";mail.SenderMail = "Test@mail.com";mail.SenderPw = "Pass@word";mail.SmtpServer = "IP地址";//收件人列表string temp = "test@mail.com;test2@mail.com;";string[] res = temp.Split(';');string content ="邮件内容";for (int i = 0; i < 2; i ++){Console.WriteLine("开始发送第" + i.ToString());mail.Send("邮件测试  " + i.ToString(), content, res);}Console.ReadLine();}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/819385.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

conda配置多版本python

安装conda 以下任选下载 Anaconda Miniconda 配置conda环境变量 比如windows&#xff0c;在配置我的电脑中的环境变量&#xff0c;在系统变量的Path中新增下面内容 需要根据实际目录进行更改 D:\soft\miniconda3 D:\soft\miniconda3\Scripts D:\soft\miniconda3\Library\bi…

MongoDB学习【二】MongoDB数据模型

MongoDB基本数据类型 1. ObjectId {"_id": ObjectId("5f7c45a9bcdd4e00018b4567") }2. 字符串(String) {"name": "John Doe","email": "john.doeexample.com" }3. 数值(Number) {"age": 30,"s…

Java的Future机制详解

Java的Future机制详解 一、为什么出现Future机制二、Future的相关类图2.1 Future 接口2.2 FutureTask 类 三、FutureTask的使用方法四、FutureTask源码分析4.1 state字段4.2 其他变量4.4 构造函数4.5 run方法及其他 一、为什么出现Future机制 常见的两种创建线程的方式。一种是…

Python进阶编程 --- 2.MySQL、pymysql、PySpark

文章目录 第一章&#xff1a;SQL基础入门1.1 数据库数据库如何存储数据 1.2 数据库和SQL的关系1.3 MySQL版本1.4 命令提示符内使用MySQL1.5 SQL概述1.5.1 SQL语言分类1.5.2 SQL语言特性 1.6 DDL库管理表管理 1.7 DML - 数据操作1.8 DQL - 查询和计算数据1.8.1 基础数据查询1.8.…

HDFS Lease详解

本文主要介绍hdfs lease的设计以及实现。 写在前面 https://www.cnblogs.com/jhcelue/p/6783076.html https://blog.csdn.net/yexiguafu/article/details/118890014 https://www.jianshu.com/p/33e1a5a2b876 https://blog.csdn.net/breakout_alex/article/details/1014569…

行业模板|DataEase批发零售大屏模板推荐

DataEase开源数据可视化分析平台于2022年6月发布模板市场&#xff08;https://templates-de.fit2cloud.com&#xff09;&#xff0c;并于2024年1月新增适用于DataEase v2版本的模板分类。模板市场旨在为DataEase用户提供专业、美观、拿来即用的大屏模板&#xff0c;方便用户根据…

LeetCode-热题100:75. 颜色分类

题目描述 给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums &#xff0c;原地对它们进行排序&#xff0c;使得相同颜色的元素相邻&#xff0c;并按照红色、白色、蓝色顺序排列。 我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。 必须在不使用库内置的 sort 函数的…

【Canvas与艺术】绘制斜置黄色三角biohazard标志

【关键点】 径向渐变色和文字按角度偏转。 【成果图】 【代码】 <!DOCTYPE html> <html lang"utf-8"> <meta http-equiv"Content-Type" content"text/html; charsetutf-8"/> <head><title>使用Html5/Canvas绘制…

spring-cloud微服务gateway

核心部分&#xff1a;routes(路由)&#xff0c; predicates(断言)&#xff0c;filters(过滤器) id&#xff1a;可以理解为是这组配置的一个id值&#xff0c;请保证他的唯一的&#xff0c;可以设置为和服务名一致 uri&#xff1a;可以理解为是通过条件匹配之后需要路由到&…

2024 CKA 基础操作教程(十二)

题目内容 考点相关内容分析 Pods Pod 是可以在 Kubernetes 中创建和管理的、最小的可部署的计算单元。 Pod 是 Kubernetes 中的原子单元&#xff0c;用于封装应用程序的一个或多个容器、存储资源、唯一的网络 IP&#xff0c;以及有关如何运行容器的选项。Pod 提供了一个共享的…

一些实用的工具网站

200 css渐变底色 https://webgradients.com/ 200动画效果复制 https://css-loaders.com/classic/ 二次贝塞尔曲线 https://blogs.sitepointstatic.com/examples/tech/canvas-curves/bezier-curve.html 三次贝塞尔曲线 https://blogs.sitepointstatic.com/examples/tech/c…

Day92:系统攻防-WindowsLinux远程探针本地自检任意执行权限提升入口点

目录 操作系统-远程漏扫-Nessus&Nexpose&Goby Nessus Nexpose 知识点&#xff1a; 1、远程漏扫-Nessus&Nexpose&Goby 2、本地漏扫-Wesng&Tiquan&Suggester 3、利用场景-远程利用&本地利用&利用条件 操作系统-远程漏扫-Nessus&Nexpose&a…

Python——详细解析目标检测xml格式标注转换为txt格式

本文简述了目标检测xml格式标注的内容&#xff0c;以及yolo系列模型所需的txt格式标注的内容。并提供了一个简单的&#xff0c;可以将xml格式标注文件转换为txt格式标注文件的python脚本。 1. xml格式文件内容 <size>标签下为图片信息&#xff0c;包括 <width> …

​​​​​​​iOS配置隐私清单文件App Privacy Configuration

推送到TestFlight后邮件收到警告信息如下&#xff0c;主要关于新的隐私政策需要补充&#xff1a; Hello, We noticed one or more issues with a recent submission for TestFlight review for the following app: AABBCC Version 10.10.10 Build 10 Although submission for …

servlet的三个重要的类(httpServlet 、httpServletRequst、 httpServletResponse)

一、httpServlet 写一个servlet代码一般都是要继承httpServlet 这个类&#xff0c;然后重写里面的方法 但是它有一个特点&#xff0c;根据之前写的代码&#xff0c;我们发现好像没有写main方法也能正常执行。 原因是&#xff1a;这个代码不是直接运行的&#xff0c;而是放到…

共模电感饱和电流和额定电流的区别

共模电感饱和电流和额定电流是两个不同的概念&#xff0c;它们的区别如下&#xff1a; 1. 定义不同&#xff1a;共模电感饱和电流是指当通过共模电感的电流超过一定值时&#xff0c;共模电感的磁芯开始饱和&#xff0c;导致电感值下降。额定电流是指共模电感在正常工作条件下…

文章解读与仿真程序复现思路——中国电机工程学报EI\CSCD\北大核心《应用图论建模输电网的电力现货市场出清模型》

本专栏栏目提供文章与程序复现思路&#xff0c;具体已有的论文与论文源程序可翻阅本博主免费的专栏栏目《论文与完整程序》 论文与完整源程序_电网论文源程序的博客-CSDN博客https://blog.csdn.net/liang674027206/category_12531414.html 电网论文源程序-CSDN博客电网论文源…

JavaSE图书管理系统实战

代码仓库地址&#xff1a;Java图书管理系统 1.前言 该项目将JavaSE的封装继承多态三大特性&#xff0c;使用了大量面向对象的操作&#xff0c;有利于巩固理解 &#xff08;1&#xff09;实现效果 2.实现步骤 第一步先把框架搭建起来&#xff0c;即创建出人&#xff1a;管理员和…

RocketMQ 02 功能大纲介绍

RocketMQ 02 主流的MQ有很多&#xff0c;比如ActiveMQ、RabbitMQ、RocketMQ、Kafka、ZeroMQ等。 之前阿里巴巴也是使用ActiveMQ&#xff0c;随着业务发展&#xff0c;ActiveMQ IO 模块出现瓶颈&#xff0c;后来阿里巴巴 通过一系列优化但是还是不能很好的解决&#xff0c;之后…

串口通信有哪些常见的应用领域?

串口通信是一种常见的数据通信方式&#xff0c;它使用串行接口在两个设备之间发送和接收数据。这种通信方式由于其简单性和广泛的支持&#xff0c;在多个应用领域中被广泛使用。下面是一些串口通信的常见应用领域&#xff1a; 工业自动化&#xff1a;串口通信在工业自动化中非常…