代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
CSharp
】
C#发送邮件的类(不用WEB.MAIL类)
作者:
zzyyll2
/ 发布于
2011/2/9
/
784
本来用SYSTEM.WEB.MAIL类来进行邮件发送的,但是发现它的附件好象不能发送文件流,只能是文件路径,
using System; using System.Collections.Generic; using System.Collections; using System.Text; using System.IO; using System.Net.Sockets; namespace CSharp_SendMail { class MailSender { private string server = ""; private int port = 25; private string userName = ""; private string password = ""; private string from = ""; private string to = ""; private string fromName = ""; private string toName = ""; private string subject = ""; private string body = ""; private string htmlbody = ""; private bool ishtml = false; private string encoding = "8bit"; private string languageEncoding = "GB2312"; private int priority = 3; private ArrayList attachments = new ArrayList(); #region Property ///<summary> /// SMTP ServerName or IP ///</summary> public string Server { get { return server; } set { server = value; } } ///<summary> ///SMTP Port[Default is 25] ///</summary> public int Port { get { return port; } set { port = value; } } ///<summary> /// Username [auth] /// </summary> public string UserName { get { return userName; } set { userName = value; } } ///<summary> ///Password[Auth.] /// </summary> public string Password { get { return password; } set { password = value; } } ///<summary> ///MailFrom /// </summary> public string From { get { return from; } set { from = value; } } ///<summary> ///MailTo ///</summary> public string To { get { return to; } set { to = value; } } ///<summary> ///FromName ///</summary> public string FromName { get { return fromName; } set { fromName = value; } } ///<summary> ///ToName /// </summary> public string ToName { get { return toName; } set { toName = value; } } ///<summary> ///Mail Subject ///</summary> public string Subject { get { return subject; } set { subject = value; } } ///<summary> ///Mail's Body /// </summary> public string Body { get { return body; } set { body = value; } } ///<summary> ///Body's Format ///</summary> public string HtmlBody { get { return htmlbody; } set { if (value != htmlbody) htmlbody = value; } } /// <summary> /// Is Html Format /// </summary> public bool IsHtml { get { return ishtml; } set { if (value != ishtml) ishtml = value; } } ///<summary> ///Language Encoding[default is GB2312] /// </summary> public string LanguageEncoding { get { return languageEncoding; } set { if (value != languageEncoding) languageEncoding = value; } } /// <summary> /// MailEncoding [default is 8bit] /// </summary> public string MailEncoding { get { return encoding; } set { if (value != encoding) encoding = value; } } ///<summary> ///Mail's Priority[default is 3] /// </summary> public int Priority { get { return priority; } set { if (value != priority)priority = value; } } ///<summary> /// Mail's Attachments /// </summary> public IList Attachments { get { return attachments; } // set { if (value != attachments)attachments = value; } } #endregion #region Method ///<summary> ///SendMail /// </summary> public void SendMail() { TcpClient tcp = null; try { tcp = new TcpClient(server, port); } catch (Exception) { throw new Exception("Connect to Server Error"); } ReadString(tcp.GetStream());//Get Connection Info // Start To Auth. // if status = 250 ,success if (!Command(tcp.GetStream(), "EHLO Localhost", "250")) throw new Exception("Login failed"); if (userName != "") { // Need Auth. if (!Command(tcp.GetStream(), "AUTH LOGIN", "334")) throw new Exception("Auth. failed"); string nameB64 = ToBase64(userName); // if (!Command(tcp.GetStream(), nameB64, "334")) throw new Exception("Auth. failed"); string passB64 = ToBase64(password); // if (!Command(tcp.GetStream(), passB64, "235")) throw new Exception("Auth. failed"); } WriteString(tcp.GetStream(), "mail From: " + from); WriteString(tcp.GetStream(), "rcpt to: " + to); WriteString(tcp.GetStream(), "data"); // Send Mail Head WriteString(tcp.GetStream(), "Date: " + DateTime.Now); // Time WriteString(tcp.GetStream(), "From: " + fromName + "(" + from + ")"); // Accept WriteString(tcp.GetStream(), "Subject: " + subject); // Title WriteString(tcp.GetStream(), "To:" + toName + "(" + to + ")"); // Acceptor //Mail Format WriteString(tcp.GetStream(), "Content-Type: multipart/mixed;boundary=\"unique-boundary-1\""); WriteString(tcp.GetStream(), "Reply-To:" + from); // WriteString(tcp.GetStream(), "X-Priority:" + priority); // WriteString(tcp.GetStream(), "MIME-Version:1.0"); // MIME Version // WriteString (tcp.GetStream(), "Message-Id: <a href="mailto:" + DateTime.Now.ToFileTime() + "@security.com">" + DateTime.Now.ToFileTime() + "@security.com</a>"); WriteString(tcp.GetStream(), "Content-Transfer-Encoding:" + encoding); WriteString(tcp.GetStream(), "X-Mailer:JcPersonal.Utility.MailSender"); WriteString(tcp.GetStream(), ""); WriteString(tcp.GetStream(), ToBase64("This is a multi-part message in MIME format.")); WriteString(tcp.GetStream(), ""); WriteString(tcp.GetStream(), "--unique-boundary-1"); WriteString(tcp.GetStream(), "Content-Type: multipart/alternative;Boundary=\"unique-boundary-2\""); WriteString(tcp.GetStream(), ""); if (!ishtml) { WriteString(tcp.GetStream(), "--unique-boundary-2"); WriteString(tcp.GetStream(), "Content-Type: text/plain;charset=" + languageEncoding); WriteString(tcp.GetStream(), "Content-Transfer-Encoding:" + encoding); WriteString(tcp.GetStream(), ""); WriteString(tcp.GetStream(), body); WriteString(tcp.GetStream(), ""); WriteString(tcp.GetStream(), "--unique-boundary-2--"); WriteString(tcp.GetStream(), ""); } else { WriteString(tcp.GetStream(), "--unique-boundary-2"); WriteString(tcp.GetStream(), "Content-Type: text/html;charset=" + languageEncoding); WriteString(tcp.GetStream(), "Content-Transfer-Encoding:" + encoding); WriteString(tcp.GetStream(), ""); WriteString(tcp.GetStream(), htmlbody); WriteString(tcp.GetStream(), ""); WriteString(tcp.GetStream(), "--unique-boundary-2--"); WriteString(tcp.GetStream(), ""); } // Send Attachments for (int i = 0; i < attachments.Count; i++) { WriteString(tcp.GetStream(), "--unique-boundary-1"); WriteString(tcp.GetStream(), "Content-Type: application/octet-stream;name=\"" + ((AttachmentInfo)attachments[i]).FileName + "\""); WriteString(tcp.GetStream(), "Content-Transfer-Encoding: base64"); WriteString(tcp.GetStream(), "Content-Disposition:attachment;filename=\"" + ((AttachmentInfo)attachments[i]).FileName + "\""); WriteString(tcp.GetStream(), ""); WriteString(tcp.GetStream(), ((AttachmentInfo)attachments[i]).Bytes); WriteString(tcp.GetStream(), ""); } Command(tcp.GetStream(), ".", "250"); // End ,Input "." // Close Connection tcp.Close(); } /// <summary> /// Write string to Stream /// </summary> /// (param name="netStream")TcpClient Stream(/param) /// (param name="str")string(/param) protected void WriteString(NetworkStream netStream, string str) { str = str + "\r\n"; byte[] bWrite = Encoding.GetEncoding(languageEncoding).GetBytes(str.ToCharArray()); int start = 0; int length = bWrite.Length; int page = 0; int size = 75; int count = size; try { if (length > 75) { if ((length / size) * size < length) page = length / size + 1; else page = length / size; for (int i = 0; i < page; i++) { start = i * size; if (i == page - 1) count = length - (i * size); netStream.Write(bWrite, start, count); } } else netStream.Write(bWrite, 0, bWrite.Length); } catch (Exception) { } } /// <summary> /// Read String Form Stream /// </summary> /// (param name="netStream")TcpClient Stream(/param) /// (returns)string(/returns) protected string ReadString(NetworkStream netStream) { string sp = null; byte[] by = new byte[1024]; int size = netStream.Read(by, 0, by.Length);// Read Stream if (size > 0) { sp = Encoding.Default.GetString(by);// Convert To string } return sp; } /// <summary> /// Send Command /// /// </summary> /// (param name="netStream")TcpClient Stream(/param) /// (param name="command")Command(/param) /// (param name="state")status(/param) /// (returns)is correct(/returns) protected bool Command(NetworkStream netStream, string command, string state) { string sp = null; bool success = false; try { WriteString(netStream, command); sp = ReadString(netStream); if (sp.IndexOf(state) != -1) success = true; } catch (Exception) { } return success; } /// <summary> /// Convert String To Base64 /// </summary> /// (param name="str")string (/param) /// (returns)Base64 string(/returns) protected string ToBase64(string str) { try { byte[] by = Encoding.Default.GetBytes(str.ToCharArray()); str = Convert.ToBase64String(by); } catch (Exception) { } return str; } #endregion #region Mail Struct /// <summary> /// Attachment Info /// </summary> public struct AttachmentInfo { private string fileName; private string bytes; public string FileName { get { return fileName; } set { fileName = Path.GetFileName(value); } } public string Bytes { get { return bytes; } set { if (value != bytes) bytes = value; } } /// <summary> /// Send Stream /// </summary> /// <param name="ifileName">File Name</param> /// <param name="stream">File Stream</param> public AttachmentInfo(string ifileName, Stream stream) { fileName = Path.GetFileName(ifileName); byte[] by = new byte[stream.Length]; stream.Read(by, 0, (int)stream.Length); bytes = Convert.ToBase64String(by); } /// <summary> /// Send bytes /// </summary> /// <param name="ifileName">File Name</param> /// <param name="ibytes">bytes</param> public AttachmentInfo(string ifileName, byte[] ibytes) { fileName = Path.GetFileName(ifileName); bytes = Convert.ToBase64String(ibytes); } /// <summary> /// Send Local File /// </summary> /// <param name="path">File Path</param> public AttachmentInfo(string path) { fileName = Path.GetFileName(path); FileStream file = new FileStream(path, FileMode.Open); byte[] by = new byte[file.Length]; file.Read(by, 0, (int)file.Length); bytes = Convert.ToBase64String(by); file.Close(); } } #endregion } } 这个类里面有个结构,AttachmentInfo有3个实现,分别可以添加STREAM ,BYTES和文件 路径。 下冇再看看如何调用 这个类来发邮件。 MailSender ms = new MailSender(); ms.From = "<a href="mailto:mailfrom@company.COM">mailfrom@company.COM</a>"; ms.To = "<a href="mailto:mailto@company.com">mailto@company.com</a>"; ms.Subject = "Subject"; ms.Body = "body text"; ms.UserName = "XXXXXX";//不能说 ms.Password = "XXXXXX";//不能说 ms.Server = "10.133.130.62"; ms.Attachments.Add(new MailSender.AttachmentInfo(@"c:\a.txt"));//发送文件 System.IO.FileStream fs = new System.IO.FileStream(@"c:\tmuninst.ini", System.IO.FileMode.Open); ms.Attachments.Add(new MailSender.AttachmentInfo("tmuninst.ini", fs));//发送文件流 Console.WriteLine("mail sending"); try { ms.SendMail(); Console.WriteLine("mail sended."); } catch (Exception ex) { Console.WriteLine(ex); }
试试其它关键字
发送邮件
同语言下
.
文件IO 操作类库
.
Check图片类型[JPEG(.jpg 、.jpeg),TIF,GIF,BMP,PNG,P
.
机器名和IP取得(IPV4 IPV6)
.
Tiff转换Bitmap
.
linqHelper
.
MadieHelper.cs
.
RegHelper.cs
.
如果关闭一个窗体后激活另一个窗体的事件或方法
.
创建日志通用类
.
串口辅助开发类
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
zzyyll2
贡献的其它代码
(
1
)
.
C#发送邮件的类(不用WEB.MAIL类)
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3