Source
//============================================================
File:MailSender.cs
Mail Send component
Support ESMTP, multiple attachments
//============================================================
Namespace Jcpersonal.utility
{
Using System;
Using System.Collections;
Using System.Net.Sockets;
Using System.IO;
Using System.Text;
<summary>
Mail transmitter
</summary>
public class MailSender
{
<summary>
SMTP Server domain name
</summary>
public string Server {
get {return server;}
set {if (Value!= server) server = value;}
private string server = "";
<summary>
SMTP server port [default is 25]
</summary>
public int Port {
get {return port;}
set {if (Value!= port) port = value;}
private int port = 25;
<summary>
User name [if authentication is required]
</summary>
public string UserName {
get {return userName;}
set {if (Value!= userName) userName = value;}
private string userName = "";
<summary>
Password [if authentication is required]
</summary>
public string Password {
get {return password;}
set {if (Value!= password) password = value;}
private String password = "";
<summary>
Sender Address
</summary>
public string from {
get {return from;}
set {if (value!= from) from = value;}
private string from = "";
<summary>
Recipient address
</summary>
public string to {
get {return to;}
set {if (value!= to) to = value;}
private String to = "";
<summary>
Sender Name
</summary>
public string FromName {
get {return fromname;}
set {if (Value!= fromname) FromName = value;}
private string fromname = "";
<summary>
Recipient Name
</summary>
public string ToName {
get {return toname;}
set {if (Value!= toname) ToName = value;}
private string toname = "";
<summary>
The subject of the message
</summary>
public string Subject {
get {return subject;}
set {if (value!= subject) Subject = value;}
private String subject = "";
<summary>
Message body
</summary>
public string Body {
get {return body;}
set {if (value!= body) BODY = value;}
private String BODY = "";
<summary>
Message body in hypertext format
</summary>
public string HtmlBody {
get {return htmlBody;}
set {if (Value!= htmlBody) htmlBody = value;}
private string htmlBody = "";
<summary>
is an HTML-formatted message
</summary>
public bool IsHTML {
get {return ishtml;}
set {if (Value!= ishtml) ishtml = value;}
private bool ishtml = false;
<summary>
language encoding [defaults to GB2312]
</summary>
public string Languageencoding {
get {return languageencoding;}
set {if (Value!= languageencoding) languageencoding = value;}
private string languageencoding = "GB2312";
<summary>
Message encoding [default is 8bit]
</summary>
public string MailEncoding {
get {return encoding;}
set {if (Value!= encoding) encoding = value;}
private string encoding = "8bit";
<summary>
Message priority [default is 3]
</summary>
public int Priority {
get {return priority;}
set {if (Value!= priority) Priority = value;}
private int priority = 3;
<summary>
Attachment [Attachmentinfo]
</summary>
Public IList Attachments {
get {return attachments;}
set {if (Value!= attachments) attachments = value;}
Private ArrayList attachments = new ArrayList ();
<summary>
Send mail
</summary>
public void SendMail ()
{
Create a TcpClient object and establish a connection
TcpClient TCP = NULL;
Try
{
TCP = new TcpClient (server, port);
}
catch (Exception)
{
throw new Exception ("Unable to connect to server");
}
ReadString (TCP. GetStream ());//Get connection Information
Start Server Authentication
If the status code is 250, it means the operation was successful.
if (! Command (TCP. GetStream (), "EHLO Localhost", "250"))
throw new Exception ("Landing phase Failure");
if (UserName!= "")
{
Authentication Required
if (! Command (TCP. GetStream (), "AUTH LOGIN", "334"))
throw new Exception ("Authentication phase failed");
String nameB64 = ToBase64 (userName); Convert username to Base64 code here
if (! Command (TCP. GetStream (), nameB64, "334"))
throw new Exception ("Authentication phase failed");
String passB64 = ToBase64 (password); Convert password to Base64 code here
if (! Command (TCP. GetStream (), passB64, "235"))
throw new Exception ("Authentication phase failed");
}
Ready to send
WriteString (TCP. GetStream (), "Mail from:" + from);
WriteString (TCP. GetStream (), "RCPT TO:" + to);
WriteString (TCP. GetStream (), "data");
Send Message headers
WriteString (TCP. GetStream (), "Date:" + DateTime.Now); Time
WriteString (TCP. GetStream (), "from:" + FromName + "<" + from + ">"); Sender
WriteString (TCP. GetStream (), "Subject:" + Subject); Theme
WriteString (TCP. GetStream (), "to:" + ToName + "<" + to + ">"); Recipient
Message format
WriteString (TCP. GetStream (), "content-type:multipart/mixed; boundary= "Unique-boundary-1");
WriteString (TCP. GetStream (), "reply-to:" + from); Reply Address
WriteString (TCP. GetStream (), "x-priority:" + Priority); Priority level
WriteString (TCP. GetStream (), "mime-version:1.0"); MIME version
Data ID, random
WriteString (TCP. GetStream (), "Message-id:" + DateTime.Now.ToFileTime () + "@security. com");
WriteString (TCP. GetStream (), "content-transfer-encoding:" + Encoding); Content encoding
WriteString (TCP. GetStream (), "X-mailer:jcpersonal.utility.mailsender"); Mail Sender
WriteString (TCP. GetStream (), "");
WriteString (TCP. GetStream (), ToBase64 ("This are a multi-part message in MIME format.");
WriteString (TCP. GetStream (), "");
Start separating input from here
WriteString (TCP. GetStream (), "--unique-boundary-1");
Defines a second separator here
WriteString (TCP. GetStream (), "content-type:multipart/alternative; boundary= "Unique-boundary-2");
WriteString (TCP. GetStream (), "");
if (!ishtml)
{
Text information
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 (), "" ")//A part is written as empty information, segmented
WriteString (TCP. GetStream (), "--unique-boundary-2--"),//separator end symbol, behind the tail more--
WriteString (TCP. GetStream (), "");
}
Else
{
HTML information
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--"),//separator end symbol, behind the tail more--
WriteString (TCP. GetStream (), "");
}
Send Attachments
Loop the file list
for (int i = 0; i < attachments. Count; i++)
{
WriteString (TCP. GetStream (), "--unique-boundary-1"); Message Content Separator
WriteString (TCP. GetStream (), "content-type:application/octet-stream;name=" "+ (Attachmentinfo) attachments). FileName + "" "); File format
WriteString (TCP. GetStream (), "content-transfer-encoding:base64"); The encoding of the content
WriteString (TCP. GetStream (), "content-disposition:attachment;filename=" "+ (Attachmentinfo) attachments). FileName + "" "); Filename
WriteString (TCP. GetStream (), "");
WriteString (TCP. GetStream (), ((attachmentinfo) attachments). Bytes); Writing the contents of a file
WriteString (TCP. GetStream (), "");
}
Command (TCP. GetStream (), ".", "250"); Finally finished, type "."
Close connection
Tcp. Close ();
}
<summary>
Writing characters to the stream
</summary>
<param name= "NetStream" > Flows from TcpClient </param>
<param name= "str" > written characters </param>
protected void WriteString (NetworkStream netstream, String str)
{
str = str + ""; Add line Feed
Convert command line to byte[]
byte[] Bwrite = encoding.getencoding (languageencoding). GetBytes (str. ToCharArray ());
//Because the size of the data written every time is limited, we set the length of the data written to 75 bytes each time, and then write it step over 75 once the command length is over.
int start=0;
int length=bwrite.length;
int page=0;
int size=75;
int count=size;
Try
{
if (length>75)
{
//Data paging
if (lengt h/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);//write data to server
}
}
Else
Netstream.write (bwrite,0,bwrite.length);
}
catch (Exception)
{
//Ignoring errors
}
///<summary>
///reads characters from the stream
///</summary>
///<param name= " NetStream "> Streams from tcpclient </param>
///<returns> read characters </returns>
protected String ReadString (NetworkStream netstream)
{
String sp = null;
byte[] by = new byte[1024];
int size = Netstream.read (by,0,by. LENGTH)//Read data stream
if (Size > 0)
{
SP = Encoding.Default.GetString (by);//Convert to String
}
return SP;
}
///<summary>
///Issue the command and determine if the return information is correct
///</summary>
///<param Name = "NetStream" > Flows from TcpClient </param>
///<param name= "command" > Command </param>
/ <param name= "state" > Correct status code </param>
///<returns> correct </returns>
protected bool Command (NetworkStream NetStream, String Command, String state)
{
string sp=null;
BOOL Success=false;
Try
{
writestring (netstream, command);//write command
SP = ReadString (NetStream); Accept the return information
if (sp. IndexOf (state)!=-1)//Determine if the status code is correct
success=true;
}
catch (Exception)
{
//Ignoring errors
}
return success;
}
<summary>
String encoding is Base64
</summary>
<param name= "str" > String </param>
<RETURNS>BASE64 encoded string </returns>
Protected string ToBase64 (String str)
{
Try
{
byte[] by = Encoding.Default.GetBytes (str. ToCharArray ());
str = convert.tobase64string (by);
}
catch (Exception)
{
Ignoring errors
}
return str;
}
<summary>
Attachment information
</summary>
public struct Attachmentinfo
{
<summary>
The file name of the attachment [automatically converts to the filename if the path is entered]
</summary>
public string FileName {
get {return fileName;}
set {FileName = Path.getfilename (value);}
private string FileName;
<summary>
Contents of attachment [composed of bytes encoded by Base64]
</summary>
public string Bytes {
get {return bytes;}
set {if (value!= bytes) bytes = value;}
private string bytes;
<summary>
Reads the attachment contents from the stream and constructs
</summary>
<param name= "Ifilename" > attachment file name </param>
<param name= "Stream" > Flow </param>
Public Attachmentinfo (string ifilename, Stream stream)
{
FileName = Path.getfilename (ifilename);
Byte[] by = new Byte [stream. Length];
Stream. Read (by,0, (int) stream. Length); Read File contents
Format conversion
bytes = Convert.tobase64string (by); Convert to Base64 encoding
}
///<summary>
///According to the given byte construct attachment
///</summary>
///<param name= "if Ilename "> file name </param>
///<param name=" ibytes "> Attachment content [bytes]</param>
Public Attachmentinfo (String ifilename, byte[] ibytes)
{
fileName = Path.getfilename (ifilename);
bytes = convert.tobase64string (ibytes);//Convert to Base64 encoding
}
<summary>
Load and construct from a file
</summary>
<param name= "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); Read File contents
Format conversion
bytes = Convert.tobase64string (by); Convert to Base64 encoding
File. Close ();
}
}
}
}
--------------------------------------------------------------------------------
Use:
MailSender ms = new MailSender ();
Ms. from = "jovenc@Xrss.com";
Ms. to = "Jovenc@pclala.net";
Ms. Subject = "Subject";
Ms. BODY = "body text";
Ms. UserName = "########"; How can I tell you?
Ms. Password = "********"; How can I tell you?
Ms. Server = "smtp.tom.com";
Ms. Attachments.Add (The new Mailsender.attachmentinfo (@ "D:est.txt"));
Console.WriteLine ("Mail Sending ...");
Try
{
Ms. SendMail ();
Console.WriteLine ("Mail sended.");
}
catch (Exception e)
{
Console.WriteLine (e);
}