C#-mailsender Message Send component source code (support ESMTP, attachment)

Source: Internet
Author: User
Tags base64 bool command line count datetime getstream int size server port
smtp| Source Code

//============================================================
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);;//here convert UserName to Base64 code

if (! Command (TCP. GetStream (), nameB64, "334"))

throw new Exception ("Authentication phase Failed");;

String passB64 = ToBase64 (password);;//here Convert password to Base64 code

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);;//Subject

WriteString (TCP. GetStream (), "to:" + ToName + "[+ to +]");


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

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, subsection

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[i]). filename + "\");;//File format

WriteString (TCP. GetStream (), "content-transfer-encoding:base64");;//Encoding of content

WriteString (TCP. GetStream (), "content-disposition:attachment;;filename=\" "+ ((attachmentinfo) attachments[i]). filename + "\");;//filename

WriteString (TCP. GetStream (), "");;

WriteString (TCP. GetStream (), ((Attachmentinfo) attachments[i]). Bytes);;//write the contents of the 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" from TcpClient stream 〈/param〉

Characters written by 〈param name= "str" 〈/param〉

protected void WriteString (NetworkStream netstream, String str)

{

str = str + "\ r \ n";;//Add line feed


Convert command line to byte[]

byte[] Bwrite = encoding.getencoding (languageencoding). GetBytes (str. ToCharArray ());;


Since the data size for each write is limited, we set the length of the data written to 75 bytes each time, and once the command length exceeds 75, it is written in steps.

int start=0;;

int length=bwrite.length;;

int page=0;;

int size=75;;

int count=size;;

Try

{

if (length〉75)

{

Data paging

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);.//write data to the server

}

}

Else

Netstream.write (bwrite,0,bwrite.length);

}

catch (Exception)

{

Ignoring errors

}

}


〈summary〉

Reading characters from the stream

〈/summary〉

〈param name= "NetStream" from TcpClient stream 〈/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 a command and determine if the return information is correct

〈/summary〉

〈param name= "NetStream" from TcpClient stream 〈/param〉

〈param name= "command" Order 〈/param〉

〈param name= "State" the correct status code 〈/param〉

〈returns〉 is 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 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" The file name of the attachment 〈/param〉

〈param name= "Stream" 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);//Read file contents

Format conversion

bytes = Convert.tobase64string (by);;//Convert to Base64 encoding

}


〈summary〉

Constructs an attachment according to the given byte

〈/summary〉

〈param name= "Ifilename" The file name of the attachment 〈/param〉

〈param name= "Ibytes" The contents of the attachment [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@tom.com";;

Ms. to = "jovenc@citiz.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 (New Mailsender.attachmentinfo (@ "D:\test.txt"))


Console.WriteLine ("Mail Sending ...");;

Try

{

Ms. SendMail ();;

Console.WriteLine ("Mail sended."); ;

}

catch (Exception e)

{

Console.WriteLine (e);;

}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.