C#通过拼接协议的方式来发送邮件类库
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Text; namespace HR.Common
{
#region SMTP Client
public class SMTPClient : TcpClient
{
/// <summary>
/// 是否链接
/// </summary>
/// <returns></returns>
public bool isConnected()
{
return Active;
} /// <summary>
/// 向服务器发送指令
/// </summary>
/// <param name="Command">指令内容</param>
public void SendCommandToServer(string Command)
{
NetworkStream ns = this.GetStream();
byte[] WriteBuffer = null;
WriteBuffer = new byte[Command.Length];
WriteBuffer = Encoding.Default.GetBytes(Command);
ns.Write(WriteBuffer, , WriteBuffer.Length);
return;
} /// <summary>
/// 返回服务器处理结果
/// </summary>
/// <returns></returns>
public string GetServerResponse()
{
int StreamSize;
string ReturnValue = "";
byte[] ReadBuffer;
NetworkStream ns = this.GetStream(); ReadBuffer = new byte[];
StreamSize = ns.Read(ReadBuffer, , ReadBuffer.Length);
if (StreamSize == )
{
return ReturnValue;
}
else
{
ReturnValue = Encoding.Default.GetString(ReadBuffer);
return ReturnValue;
}
} /// <summary>
/// 生成SMTPCode
/// </summary>
/// <param name="s">信息内容</param>
/// <param name="SMTPCode">SMTPCode</param>
/// <returns></returns>
public bool DoesStringContainSMTPCode(string s, string SMTPCode)
{
return (s.IndexOf(SMTPCode, , ) == -) ? false : true;
} }
#endregion #region SckMail
public class SckMail
{
/// <summary>
/// 邮件发送优先级权举表
/// </summary>
public enum Prioritys
{
/// <summary>
/// 最高级别
/// </summary>
HIGH = ,
/// <summary>
/// 默认级别
/// </summary>
NORMAL = ,
/// <summary>
/// 最低级别
/// </summary>
LOW =
} /// <summary>
/// 构造函数
/// </summary>
public SckMail()
{
strErrMessage = "";
strResponse = "";
} #region "返回信息" /// <summary>
/// SMTP服务器反馈的信息
/// </summary>
private string strResponse = ""; /// <summary>
/// 取得SMTP服务器反馈的信息
/// </summary>
public string ServerResponse
{
get
{
return strResponse;
}
} /// <summary>
/// 错误反馈信息
/// </summary>
private string strErrMessage = ""; /// <summary>
/// 取得错误反馈信息
/// </summary>
public string ErrorMessage
{
get
{
return strErrMessage;
}
} /// <summary>
/// 认证用户名
/// </summary>
private string strUsername = ""; /// <summary>
/// 认证用户名
/// </summary>
public string Username
{
get { return strUsername; }
set { strUsername = value; }
} /// <summary>
/// 认证密码
/// </summary>
private string strPassword = ""; /// <summary>
/// 认证密码
/// </summary>
public string Password
{
get { return strPassword; }
set { strPassword = value; }
} #endregion #region "邮件属性" /// <summary>
/// SMTP 邮件服务器
/// </summary>
private string _SmtpHost = ""; /// <summary>
/// SMTP 邮件服务器
/// </summary>
public string SmtpHost
{
get
{
return _SmtpHost;
}
set
{
_SmtpHost = value;
}
} /// <summary>
/// SMTP邮件服务器端口
/// </summary>
private int _Port = ; /// <summary>
/// SMTP邮件服务器端口
/// </summary>
public int Port
{
get
{
return _Port;
}
set
{
_Port = value;
}
} #endregion /// <summary>
/// Base64加密
/// </summary>
/// <param name="code">明文</param>
/// <returns>密文</returns>
public string MailBase64(string code)
{
string encode = "";
try
{
byte[] bytes = Encoding.GetEncoding(Encoding.Default.CodePage).GetBytes(code);
encode = Convert.ToBase64String(bytes);
}
catch (Exception ex)
{
//utils.LastError = ex;
encode = code;
}
return encode;
} /// <summary>
/// Socket发送邮件
/// </summary>
/// <param name="strFrom">发送人 邮件地址</param>
/// <param name="strDisplayFromName">发送人显示名</param>
/// <param name="strTo">收件人 邮件地址</param>
/// <param name="strDisplayToName">收件人显示名</param>
/// <param name="clsPriority">邮件优先级</param>
/// <param name="blnHtml">是否发送HTML邮件</param>
/// <param name="strBase">发送来源(可以为空)</param>
/// <param name="strMessage">发送内容</param>
/// <param name="strSubject">邮件主题</param>
public void SendMail(string strFrom, string strDisplayFromName, string strTo, string strDisplayToName,
Prioritys clsPriority, bool blnHtml, string strBase, string strSubject, string strMessage)
{
string strResponseNumber = "";
bool bolConnect = false;
List<string> strSendBuffer = null;
string[] strResponseCode = { "", "", "", "", "", "", "" }; // success codes from SMTP server try
{
strSendBuffer = new List<string>(); SMTPClient smtpcMail = new SMTPClient(); smtpcMail.Connect(_SmtpHost, _Port);
bolConnect = smtpcMail.isConnected(); //判断是否进行了连接
if (!bolConnect)
{
strErrMessage = "Smtp服务器连接失败...";
return;
} //读取反馈信息
strResponseNumber = smtpcMail.GetServerResponse();
if (smtpcMail.DoesStringContainSMTPCode(strResponseNumber, ""))
{
this.strResponse += strResponseNumber;
}
else
{
this.strErrMessage = "连接失败:" + strResponseNumber;
return;
} string strData = "";
strData = string.Concat("HELO ", _SmtpHost);
strData = string.Concat(strData, "\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat(strData, "AUTH LOGIN");
strData = string.Concat(strData, "\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat(strData, MailBase64(this.strUsername));
strData = string.Concat(strData, "\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat(strData, MailBase64(this.strPassword));
strData = string.Concat(strData, "\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat("MAIL FROM: ", "<" + strFrom + ">");
strData = string.Concat(strData, "\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat("RCPT TO: ", "<" + strTo + ">");
strData = string.Concat(strData, "\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat("DATA", "\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat("From: ", strDisplayFromName + "<" + strFrom + ">");
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "To: ");
strData = string.Concat(strData, strDisplayToName + "<" + strTo + ">");
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "Subject: ");
strData = string.Concat(strData, strSubject);
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "MIME-Version: 1.0");
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "X-Priority: " + clsPriority);
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "X-MSMail-Priority: " + clsPriority);
strData = string.Concat(strData, "\r\n");
if (blnHtml == true)
{
strData = string.Concat(strData, "Content-Type: text/html;");
}
else
{
strData = string.Concat(strData, "Content-Type: text/plain;");
}
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "charset=\"iso-8859-1\"");
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "Content-Transfer-Encoding: base64");
strData = string.Concat(strData, "\r\n");
strData = string.Concat(strData, "Content-Base: \"" + strBase + "\"");
strData = string.Concat(strData, "\r\n" + "\r\n"); strData = string.Concat(strData, MailBase64(strMessage));
strData = string.Concat(strData, "\r\n.\r\n");
strSendBuffer.Add(strData); strData = "";
strData = string.Concat(strData, "QUIT\r\n");
strSendBuffer.Add(strData);
int i = ; while (i < strSendBuffer.Count)
{
smtpcMail.SendCommandToServer(strSendBuffer[i]);
strResponseNumber = smtpcMail.GetServerResponse(); for (int j = ; j < strResponseCode.Length; j++)
{
if (smtpcMail.DoesStringContainSMTPCode(strResponseNumber, strResponseCode[j]))
{
this.strResponse += strResponseNumber;
this.strResponse += "<br>";
break;
}
else
{
if (j == strResponseCode.Length - )
{
this.strErrMessage += strResponseNumber;
this.strErrMessage += strSendBuffer[i];
return;
}
}
} i++;
} // 结束循环
}
catch (SocketException err)
{
this.strErrMessage += err.Message + " " + err.StackTrace;
throw (err);
}
catch (Exception e)
{
this.strErrMessage += e.Message + " " + e.StackTrace;
throw (e);
}
} }
#endregion #region SMTPMail
public class SMTPMail
{
private string smtpServer;
private string smtpUser;
private string smtpPwd;
private string userEmail;
private string subject;
private string body; private int serverPort = ; //默认为25
private bool isHtml = false; // 是否Html邮件 //private string charset = "GB2312"; //设定语言代码,默认设定为GB2312,如不需要可设置为""
//private string priority = "Normal"; //邮件发送优先级,可设置为"High","Normal","Low" /// <summary>
/// 邮件服务器地址
/// </summary>
public string SmtpServer
{
get { return smtpServer; }
set { smtpServer = value; }
} /// <summary>
/// 邮件服务器端口号
/// </summary>
public int ServerPort
{
get { return serverPort; }
set { serverPort = value; }
} /// <summary>
/// 是否Html邮件
/// </summary>
public bool IsHtml
{
get { return isHtml; }
set { isHtml = value; }
} ///// <summary>
///// 代码
///// </summary>
//public string Charset
//{
// get { return charset; }
// set { charset = value; }
//}
///// <summary>
///// 邮件发送优先级,可设置为"High","Normal","Low"或"1","3","5"
///// </summary>
//public string Priority
//{
// set
// {
// switch (value.ToLower())
// {
// case "high":
// priority = "High";
// break; // case "1":
// priority = "High";
// break; // case "normal":
// priority = "Normal";
// break; // case "3":
// priority = "Normal";
// break; // case "low":
// priority = "Low";
// break; // case "5":
// priority = "Low";
// break; // default:
// priority = "High";
// break;
// }
// }
//} /// <summary>
/// 邮件发送帐号
/// </summary> public string SmtpUser
{
get { return smtpUser; }
set { smtpUser = value; }
} /// <summary>
/// 邮件发送帐号密码
/// </summary>
public string SmtpPwd
{
get { return smtpPwd; }
set { smtpPwd = value; }
} /// <summary>
/// 用户邮件地址,即是被发送人的邮件地址
/// </summary>
public string UserEmail
{
get { return userEmail; }
set { userEmail = value; }
} /// <summary>
/// 邮件标题
/// </summary>
public string Subject
{
get { return subject; }
set { subject = value; }
} /// <summary>
/// 邮件主体
/// </summary>
public string Body
{
get { return body; }
set { body = value; }
} /// <summary>
/// 发送邮件
/// </summary>
/// <returns>bool</returns>
public bool SendEmail()
{
try
{
using (MailMessage mailMsg = new MailMessage(this.smtpUser, this.userEmail))
{
mailMsg.Subject = this.subject;
mailMsg.Body = this.body;
mailMsg.SubjectEncoding = Encoding.UTF8; mailMsg.BodyEncoding = Encoding.UTF8;
mailMsg.IsBodyHtml = this.isHtml;
mailMsg.Priority = MailPriority.Normal; SmtpClient smtpClient = new SmtpClient(this.smtpServer);
smtpClient.Port = this.serverPort;
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential(this.smtpUser, this.smtpPwd);
smtpClient.Send(mailMsg); return true;
} }
catch (Exception ex)
{ throw ex;
}
}
}
#endregion #region MailInfo
public class MailInfo
{
/// <summary>
/// 邮件服务器地址
/// </summary>
public string SmtpHost = string.Empty; /// <summary>
/// 端口号
/// </summary>
public int Port = ; /// <summary>
/// 邮箱登录名
/// </summary>
public string UserName = string.Empty; /// <summary>
/// 邮箱登录密码
/// </summary>
public string Password = string.Empty; /// <summary>
/// 发送人邮件
/// </summary>
public string From = string.Empty; /// <summary>
/// 发送人姓名
/// </summary>
public string FromName = string.Empty;
/// <summary>
/// 获取邮件配置信息
/// </summary>
/// <returns></returns>
public MailInfo GetMailInfo()
{
var config = System.Web.Configuration.WebConfigurationManager.AppSettings;
MailInfo model = new MailInfo();
model.SmtpHost = config["SmtpHost"].Trim();
try
{
if (!int.TryParse(config["SmtpPort"], out model.Port))
{
model.Port = ;
}
}
catch
{
model.Port = ;
}
model.UserName = config["EmailUserName"];
model.Password = config["EmailPassword"];
model.From = config["EmailFrom"];
model.FromName = config["EmailFromName"];
return model;
}
public static string SendMail(string email, string title, string content)
{
// bool IsSuccess = true;
string mailContent = string.Empty;
string mailinfo = string.Empty;
SckMail mail = null;
MailInfo mi =new MailInfo();
try
{
mail = new SckMail();
mi = mi.GetMailInfo();
mail.SmtpHost = mi.SmtpHost;
mail.Port = mi.Port;
mail.Username = mi.From;
mail.Password = mi.Password;
mailContent = content;
mail.SendMail
(
mi.From,
mi.FromName,
email,
email,
SckMail.Prioritys.NORMAL,
true,
"",
CheckStr(title),
mailContent
);
if (mail.ErrorMessage != "")
{
mailinfo = mail.ErrorMessage;
}
}
catch (Exception e)
{
mailinfo = e.Message;
}
finally
{
mail = null;
}
return mailinfo;
}
public static string CheckStr(object str)
{
string ret = "";
try
{
if (str == null) ret = "";
else
{
ret = str.ToString();
ret = ret.Replace("'", "''");
}
}
catch
{
ret = "";
}
return ret;
}
}
#endregion
}
C#通过拼接协议的方式来发送邮件类库的更多相关文章
- hql语句拼接的替换方式
hql语句拼接的替换方式 hql语句拼接 String hql = "FROM Topic t WHERE t.forum=? "; List<Object> para ...
- HTTP协议请求方式: 中GET、POST和HEAD的介绍以及错误提示码
HTTP协议中GET.POST和HEAD的介绍 2008-05-10 14:15 GET: 请求指定的页面信息,并返回实体主体. HEAD: 只请求页面的首部. POST: 请求服务器接受所指定的文档 ...
- Json对象和字符串互相转换 数据拼接 JSON使用方式
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式. 一.JSON字符串转换为JSON对象: eval() 和 JSON.parse eg- json字符串: ...
- HTTP协议请求方式: 中GET、POST和HEAD的介绍_孤帆一叶
HTTP协议中GET.POST和HEAD的介绍 2008-05-10 14:15 GET: 请求指定的页面信息,并返回实体主体.HEAD: 只请求页面的首部.POST: 请求服务器接受所指定的文档作为 ...
- 使用 EWS(Exchange Web Service)协议读取邮件、发送邮件
问题: 公司之前可以通过POP3协议收发邮件,因而在SoapUI中用JavaMail可以读取邮件,后来配置了Office 365,POP3协议端口不再开放,邮件全部读取失败,报login timeou ...
- Linux三种SSH协议登陆方式
在实际工作中遇到了三种不同SSH协议登陆Linux服务器的方式,由简单到复杂分别阐述:一.最简单也是最不安全的root账号密码登陆通过root账号+root密码登陆Linux服务器. 二.普通用户登陆 ...
- ctfhub技能树—web前置技能—http协议—请求方式
打开靶机环境(每次打开都要30金币,好心疼啊) 题目描述为"请求方式" HTTP的请求方式共有八种 1.OPTIONS 返回服务器针对特定资源所支持的HTTP请求方法,也可以利用向 ...
- C#使用简单邮件传输协议(SMTP)发送邮件
1.首先引入命名空间: using System.Net.Mail; 2.定义邮件配置类: public class EmailServiceConfig { /// <summary> ...
- Http协议Get方式获取图片
一. 二. 我试了试,Post方式也行啊,干嘛要叫强调Get方式,费解~~ 答曰:get是向服务器请求数据,p ...
随机推荐
- 一台电脑上运行两个tomcat
1.建立两个文件夹,tomcat1,tomcat2,分别在里面放入tomcat7文件(非安装版) 2.改配置 tomcat1中的配置就不用改了,直接用默认配置 tomcat2中的配置要改要,改conf ...
- elastic job 动态设置定时任务
1. 版本 <!-- import elastic-job lite core --> <dependency> <groupId>com.dangdang< ...
- php动态链接扩展库
文章来源:http://keping.me/php-call-so/ PHP调用C/C++动态链接库 David June 19, 2013 C++, Linux, Study 摘要 有时候,单纯依靠 ...
- Spring 框架(二)
1AOP 1.1 AOP介绍 1.1.1 什么是AOP l 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功 ...
- 边缘检测matlab算法汇总
边缘检测matlab算法汇总 1. 基于一阶微分算子检测边缘图像 一阶微分边缘算子又称梯度边缘算子,它是利用图像在边缘处的阶跃性,及图像梯度在边缘去得极大值得特征性进行边缘检测. Sobel ...
- Java 之数组(4)
什么是数组: 问:编写代码保存 4 名学生的考试成绩. 答:简单啊,定义 4 个变量呗 问:那“计算全年级 400 名学生的考试成绩”,肿么办 答: ....... 数组,就可以帮助你妥妥的解决问题啦 ...
- SpringBoot框架下基于Junit的单元测试
前言 Junit是一个Java语言的单元测试框架,被开发者用于实施对应用程序的单元测试,加快程序编制速度,同时提高编码的质量.是一个在发展,现在已经到junit5,在javaEE开发中与很多框架相集成 ...
- babel的使用以及安装配置
简介 babel是一个广泛使用的转码器,可以将ES6代码转化为ES5代码,从而在现有环境执行,这意味着,你可以现在就用ES6编写程序,而不用担心现有环境是否支持. 安装及配置 npm install ...
- qt 创建资源文件
我们编写的gui可能需要一些额外的资源(比如贴图用的图片),可用资源文件统一管理.以下以图片为例. 用qt creator 打开工程,为工程新建资源文件: 命名为“项目名.prc”,(此处为“cloc ...
- WPF控件相对位置解析
WPF控件相对位置的获取方法是比较简单的.对于初学者来说,掌握这一技巧的应用,可以帮助以后对WPF的深入学习,而且在实际使用中,这是一个非常常用的方法. 我们知道WPF有着比较灵活的布局方式,关于某个 ...