Excel中有这样的资料E-mail 名字 项目1 项目2 项目3 项目4 项目5
[email protected] a111 abc def gha asd asdf
[email protected] b222 dfjd dj djf kdj asdj
[email protected] c333 dfjd dj djf kdj asdj
[email protected] d444 hkkp gu fui oioh jhgj
.........
现要做一邮件群发送程序,根据根据不同的地址发送相应的资料,要支持预览与增加备注例如:
需要向a111,b222,c333这些人发邮件,根据相应名字把对应的资料发送到对应的邮箱里;需要向d444增加备注时,能单独预览将要发送的邮件,并自由增加相应备注后发送。能提供可以实行的程序者立刻送分!
[email protected] a111 abc def gha asd asdf
[email protected] b222 dfjd dj djf kdj asdj
[email protected] c333 dfjd dj djf kdj asdj
[email protected] d444 hkkp gu fui oioh jhgj
.........
现要做一邮件群发送程序,根据根据不同的地址发送相应的资料,要支持预览与增加备注例如:
需要向a111,b222,c333这些人发邮件,根据相应名字把对应的资料发送到对应的邮箱里;需要向d444增加备注时,能单独预览将要发送的邮件,并自由增加相应备注后发送。能提供可以实行的程序者立刻送分!
一个循环出来,将E-mail字段的值用变量串起来。比如:str="[email protected];[email protected]";
然后将此变量赋给email.To属性,即可群发
描述:邮件发送常见问题解决方法
真的挺麻烦
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;namespace TaskManageDesigner//Mail
{
public enum MailPriority {High, Normal, Low};
public enum MailFormat {Text, Html}; public class SmtpMail
{ private string enter="\r\n"; #region Property
/// <summary>
/// charset, default is GB2312, if not required, set it to ""
/// </summary>
private string _charset="GB2312";
public string Charset
{
get
{
return this._charset;
}
set
{
this._charset = value;
}
} /// <summary>
/// mail from address
/// </summary>
private string _from="";
public string From
{
get
{
return _from;
}
set
{
this._from = value;
}
} /// <summary>
/// FromName
/// </summary>
private string _fromName="";
public string FromName
{
get
{
return this._fromName;
}
set
{
this._fromName = value;
}
} private string _recipientName="";
public string RecipientName
{
get
{
return this._recipientName;
}
set
{
this._recipientName = value;
}
} private Hashtable Recipient=new Hashtable();
private Hashtable CCRecipient = new Hashtable(); private string mailserver=""; // mail server portk, default is 25
private int mailserverport=25;
public int MailDomainPort
{
set
{
mailserverport=value;
}
} // authentication user name
private string username=""; // authentication password
private string password=""; // is esmtp, require authentication
private bool ESmtp=false; // is html format
private bool _html=false; // Attachment files
private IList Attachments; private string priority = "Normal";
//can set :"High","Normal","Low"
public MailPriority Priority
{
set
{
priority = value.ToString();
}
}
// mail subject
private string _subject;
public string Subject
{
get
{
return this._subject;
}
set
{
this._subject = value;
}
} // mail body
private string _body;
public string Body
{
get
{
return this._body;
}
set
{
this._body = value;
}
} private string errmsg; private TcpClient tc;
private NetworkStream ns;
private string logs=""; /// SMTP error code
private Hashtable ErrCodeHT = new Hashtable(); /// SMTP information code
private Hashtable RightCodeHT = new Hashtable();
/// <summary>
/// mail server and authentication information
/// format1: "user:[email protected]:25"
/// format2: "user:[email protected]"
/// format3: "www.server.com"
/// </summary>
public string MailDomain
{
set
{
string maidomain=value.Trim();
int tempint; if(maidomain!="")
{
tempint=maidomain.IndexOf("@");
if(tempint!=-1)
{
string str=maidomain.Substring(0,tempint);
MailServerUserName=str.Substring(0,str.IndexOf(":"));
MailServerPassWord=str.Substring(str.IndexOf(":")+1,str.Length-str.IndexOf(":")-1);
maidomain=maidomain.Substring(tempint+1,maidomain.Length-tempint-1);
} tempint=maidomain.IndexOf(":");
if(tempint!=-1)
{
mailserver=maidomain.Substring(0,tempint);
mailserverport=System.Convert.ToInt32(maidomain.Substring(tempint+1,maidomain.Length-tempint-1));
}
else
{
mailserver=maidomain; }
} }
} public string MailServerUserName
{
set
{
if(value.Trim()!="")
{
username=value.Trim();
ESmtp=true;
}
else
{
username="";
ESmtp=false;
}
}
} public string MailServerPassWord
{
set
{
password=value;
}
} public MailFormat Format
{
set
{
switch (value)
{
case MailFormat.Html:
this._html = true;
break;
case MailFormat.Text:
this._html = false;
break;
default:
this._html = true;
break;
}
}
}
public string ErrorMessage
{
get
{
return errmsg;
}
} public string Logs
{
get
{
return logs;
}
}
#endregion #region public functions
public SmtpMail()
{
Attachments = new System.Collections.ArrayList();
} /// <summary>
/// add attachment file
/// </summary>
/// <param name="FilePath">file absolute path</param>
public void AddAttachment(params string[] FilePath)
{
if(FilePath==null)
{
throw(new ArgumentNullException("FilePath"));
}
for(int i=0;i<FilePath.Length;i++)
{
Attachments.Add(FilePath[i]);
}
} public bool Send()
{
if(mailserver.Trim()=="")
{
throw(new ArgumentNullException("Recipient","Must set SMTP server"));
}
return SendEmail();
} public bool Send(string smtpserver)
{
MailDomain=smtpserver;
return Send();
} public bool Send(string smtpserver,string from,string fromname,
string to,string toname, bool html,
string subject,string body)
{
MailDomain=smtpserver;
From=from;
FromName=fromname;
AddRecipient(to);
RecipientName=toname;
this._html = html;
Subject=subject;
Body=body;
return Send();
}
/// <summary>
/// add a Recipient
/// </summary>
/// <param name="Recipients">Recipient address </param>
private bool AddRecipient(string Recipients)
{
if (Recipients==null||Recipients.Trim()=="")
return false;
Recipient.Add(Recipient.Count, Recipients);
return true;
} public bool AddRecipientLongStr(string pcLongStr)
{
bool llRetVal=false;
if (pcLongStr==null&&pcLongStr.Trim()=="")
return false;
string[] lstrarr = pcLongStr.Split(',');
for (int i=0;i<lstrarr.Length;i++)
{
llRetVal=llRetVal&AddRecipient(lstrarr[i]);
}
return llRetVal;
}
======jiexia
public bool AddRecipient(params string[] Recipients)
{
if(Recipient==null)
{
throw(new ArgumentNullException("Recipients"));
}
for(int i=0;i<Recipients.Length;i++)
{
string recipient = Recipients[i].Trim();
if(recipient==String.Empty)
{
throw(new ArgumentNullException("Recipients["+ i +"]"));
}
if(recipient.IndexOf("@")==-1)
{
throw(new ArgumentException("Recipients.IndexOf(\"@\")==-1","Recipients"));
}
if(!AddRecipient(recipient))
{
return false;
}
}
return true;
} //cc to
public bool AddCCRecipient(string str)
{
if(str==null||str.Trim()=="")
return false;
CCRecipient.Add(CCRecipient.Count, str);
return true;
} public bool AddCCRecipientLongStr(string pclongstr)
{
bool llRetVal=false;
if (pclongstr==null&&pclongstr.Trim()=="")
return false;
string[] lstrarr = pclongstr.Split(',');
for (int i=0;i<lstrarr.Length;i++)
{
llRetVal=llRetVal&AddCCRecipient(lstrarr[i]);
}
return llRetVal;
} public bool AddCCRecipient(params string[] str)
{
if(this.CCRecipient==null)
{
throw(new ArgumentNullException("CCRecipients"));
}
for(int i=0;i<str.Length;i++)
{
string recipient = str[i].Trim();
if(recipient==String.Empty)
{
throw(new ArgumentNullException("CCRecipients["+ i +"]"));
}
if(recipient.IndexOf("@")==-1)
{
throw(new ArgumentException("Recipients.IndexOf(\"@\")==-1","CCRecipients"));
}
if(!AddRecipient(recipient))
{
return false;
}
}
return true;
}
#endregion void Dispose()
{
if(ns!=null)ns.Close();
if(tc!=null)tc.Close();
} #region helper fucntions #region smtp error code
/// <summary>
/// SMTP response
/// </summary>
private void SMTPCodeAdd()
{
ErrCodeHT.Add("500", "Syntax error, command unrecognized. Also command line too long");
ErrCodeHT.Add("501", "Syntax error in paramaters or arguements");
ErrCodeHT.Add("502", "Command not implemented ");
ErrCodeHT.Add("503", "Bad sequence of commands ");
ErrCodeHT.Add("504", "Command parameters not implemented "); ErrCodeHT.Add("421","service not available, closing transmission channel");
ErrCodeHT.Add("450","Requested action not taken; mailbox unavilable or busy ");
ErrCodeHT.Add("550","Action not taken. Mailbox unavailable. Not found, not accessible");
ErrCodeHT.Add("451","Requested action aborted, local error in processing ");
ErrCodeHT.Add("551","User not local, please try");
ErrCodeHT.Add("452","Requested action not taken, insufficient system storage");
ErrCodeHT.Add("552","Exceeded storage allocation");
ErrCodeHT.Add("553","Mailbox name not allowed. Mailbox syntax may be incorrect");
ErrCodeHT.Add("554", "Transaction failed ");
ErrCodeHT.Add("432","Require password transform ");
ErrCodeHT.Add("534","Authentication service is simply");
ErrCodeHT.Add("538","Authentication require security");
ErrCodeHT.Add("454","Tempory authentication failed");
ErrCodeHT.Add("530","Require authentication"); RightCodeHT.Add("220","Service ready");
RightCodeHT.Add("250","Requested mail action okay, completed ");
RightCodeHT.Add("251","User not local; will forward to ");
RightCodeHT.Add("354","Start mail input; end with ");
RightCodeHT.Add("221","Service closing transmission channel ");
RightCodeHT.Add("334","Service response vertify Base64 string");
RightCodeHT.Add("235","authentication success");
}
#endregion /// string to Base64 string
private string Base64Encode(string str)
{
byte[] barray;
barray=Encoding.Default.GetBytes(str);
return Convert.ToBase64String(barray);
}
// Base 64 string to string
private string Base64Decode(string str)
{
byte[] barray;
barray=Convert.FromBase64String(str);
return Encoding.Default.GetString(barray);
} /// <param name="FilePath">file absolute path</param>
private string GetStream(string FilePath)
{
System.IO.FileStream FileStr=new System.IO.FileStream(FilePath,System.IO.FileMode.Open);
byte[] by = new byte[System.Convert.ToInt32(FileStr.Length)];
FileStr.Read(by,0,by.Length);
FileStr.Close();
return(System.Convert.ToBase64String(by));
} /// <summary>
/// send command
/// </summary>
private bool SendCommand(string str)
{
byte[] WriteBuffer;
if(str==null||str.Trim()==String.Empty)
{
return true;
}
logs+=str;
WriteBuffer = Encoding.Default.GetBytes(str);
try
{
ns.Write(WriteBuffer,0,WriteBuffer.Length);
}
catch
{
errmsg = "net connection error";
return false;
}
return true;
} /// <summary>
/// receive response
/// </summary>
private string RecvResponse()
{
int StreamSize;
string ReturnValue = String.Empty;
byte[] ReadBuffer = new byte[1024] ;
try
{
StreamSize=ns.Read(ReadBuffer,0,ReadBuffer.Length);
}
catch
{
errmsg = "net connection error";
return "false";
} if (StreamSize==0)
{
return ReturnValue ;
}
else
{
ReturnValue = Encoding.Default.GetString(ReadBuffer).Substring(0,StreamSize);
logs+=ReturnValue+this.enter;
return ReturnValue;
}
} /// <summary>
/// send a command and receive a response
/// </summary>
/// <param name="str">command</param>
/// <param name="errstr">response</param>
private bool Dialog(string str,string errstr)
{
if(str==null||str.Trim()=="")
{
return true;
}
if(SendCommand(str))
{
string RR=RecvResponse();
if(RR=="false")
{
return false;
}
string RRCode=RR.Substring(0,3);
if(RightCodeHT[RRCode]!=null)
{
return true;
}
else
{
if(ErrCodeHT[RRCode]!=null)
{
errmsg+=(RRCode+ErrCodeHT[RRCode].ToString());
errmsg+=enter;
}
else
{
errmsg+=RR;
}
errmsg+=errstr;
return false;
}
}
else
{
return false;
} }
/// dialog with server, send a seires command and recieve response
/// </summary>
private bool Dialog(string[] str,string errstr)
{
for(int i=0;i<str.Length;i++)
{
if(!Dialog(str[i],""))
{
errmsg+=enter;
errmsg+=errstr;
return false;
}
} return true;
} /// <summary>
/// SendEmail
/// </summary>
/// <returns></returns>
private bool SendEmail()
{
//connection
try
{
tc=new TcpClient(mailserver,mailserverport);
}
catch(Exception e)
{
errmsg=e.ToString();
return false;
} ns = tc.GetStream();
SMTPCodeAdd(); //vertify net
if(RightCodeHT[RecvResponse().Substring(0,3)]==null)
{
errmsg = "net connection error";
return false;
}
string[] SendBuffer;
string SendBufferstr; //esmtp
if(ESmtp)
{
SendBuffer=new String[4];
SendBuffer[0]="EHLO " + mailserver + enter;
SendBuffer[1]="AUTH LOGIN" + enter;
SendBuffer[2]=Base64Encode(username) + enter;
SendBuffer[3]=Base64Encode(password) + enter;
if(!Dialog(SendBuffer,"SMTP server authentication failed"))
return false;
}
else
{
SendBufferstr="HELO " + mailserver + enter;
if(!Dialog(SendBufferstr,""))
return false;
} SendBufferstr="MAIL FROM:<" + From + ">" + enter;
if(!Dialog(SendBufferstr, "FromUser address error, or is empty"))
return false; //
int recp = Recipient.Count + CCRecipient.Count;
SendBuffer = new string[recp];
for(int i=0; i< Recipient.Count;i++)
{
SendBuffer[i]="RCPT TO:<" + Recipient[i].ToString() +">" + enter; }
for(int i=0; i < CCRecipient.Count;i++)
{
SendBuffer[2] = "RCPT TO:<" + CCRecipient[i].ToString() +">" + enter; }
if(!Dialog(SendBuffer,"Recipient error"))
return false; SendBufferstr="DATA" + enter;
if(!Dialog(SendBufferstr,""))
return false; SendBufferstr="From:" + FromName + "<" + From +">" +enter; //if(ReplyTo.Trim()!="")
//{
// SendBufferstr+="Reply-To: " + ReplyTo + enter;
//} //SendBufferstr+="To:" + RecipientName + "<" + Recipient[0] +">" +enter;
if (Recipient.Count == 1)
SendBufferstr += "To:=?"+Charset.ToUpper()+"?B?"+Base64Encode(RecipientName)+"?="+"<"+Recipient[0]+">"+enter;
else
{
SendBufferstr+="To:";
for(int i=0;i<Recipient.Count;i++)
{
SendBufferstr+=Recipient[i].ToString() + "<" + Recipient[i].ToString() +">,";
}
SendBufferstr+=enter;
}
SendBufferstr+="CC:";
for(int i=0;i< CCRecipient.Count;i++)
{
SendBufferstr+=CCRecipient[i].ToString() + "<" + CCRecipient[i].ToString() +">,";
}
SendBufferstr+=enter; SendBufferstr+=((Subject==String.Empty || Subject==null)?"Subject:":((Charset=="")?("Subject:" + Subject):("Subject:" + "=?" + Charset.ToUpper() + "?B?" + Base64Encode(Subject) +"?="))) + enter;
SendBufferstr+="X-Priority:" + priority + enter;
SendBufferstr+="X-MSMail-Priority:" + priority + enter;
SendBufferstr+="Importance:" + priority + enter;
SendBufferstr+="X-Mailer: Lion.Web.Mail.SmtpMail Pubclass [cn]" + enter;
SendBufferstr+="MIME-Version: 1.0" + enter;
if(Attachments.Count!=0)
{
SendBufferstr+="Content-Type: multipart/mixed;" + enter;
SendBufferstr += " boundary=\"====="+(this._html?"001_Dragon520636771063_":"001_Dragon303406132050_")+"=====\""+enter+enter;
} if(this._html)
{
if(Attachments.Count==0)
{
//content type
SendBufferstr += "Content-Type: multipart/alternative;"+enter;
SendBufferstr += " boundary=\"=====003_Dragon520636771063_=====\""+enter+enter; SendBufferstr += "This is a multi-part message in MIME format."+enter+enter;
}
else
{
SendBufferstr +="This is a multi-part message in MIME format."+enter+enter;
SendBufferstr += "--=====001_Dragon520636771063_====="+enter;
SendBufferstr += "Content-Type: multipart/alternative;"+enter;
SendBufferstr += " boundary=\"=====003_Dragon520636771063_=====\""+enter+enter;
}
SendBufferstr += "--=====003_Dragon520636771063_====="+enter;
SendBufferstr += "Content-Type: text/plain;"+ enter;
SendBufferstr += ((Charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" + Charset.ToLower() + "\"")) + enter;
SendBufferstr+="Content-Transfer-Encoding: base64" + enter + enter;
SendBufferstr+= Base64Encode("Mail content is HTML format, please view with HTML") + enter + enter; SendBufferstr += "--=====003_Dragon520636771063_====="+enter;
SendBufferstr+="Content-Type: text/html;" + enter;
SendBufferstr+=((Charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" + Charset.ToLower() + "\"")) + enter;
SendBufferstr+="Content-Transfer-Encoding: base64" + enter + enter;
SendBufferstr+= Base64Encode(Body) + enter + enter;
SendBufferstr += "--=====003_Dragon520636771063_=====--"+enter;
}
else
{
if(Attachments.Count!=0)
{
SendBufferstr += "--=====001_Dragon303406132050_====="+enter;
}
SendBufferstr+="Content-Type: text/plain;" + enter;
SendBufferstr+=((Charset=="")?(" charset=\"iso-8859-1\""):(" charset=\"" + Charset.ToLower() + "\"")) + enter;
SendBufferstr+="Content-Transfer-Encoding: base64" + enter + enter;
SendBufferstr+= Base64Encode(Body) + enter;
}
//SendBufferstr += "Content-Transfer-Encoding: base64"+enter;
if(Attachments.Count!=0)
{
for(int i=0;i<Attachments.Count;i++)
{
string filepath = (string)Attachments[i];
SendBufferstr += "--====="+ (this._html?"001_Dragon520636771063_":"001_Dragon303406132050_") +"====="+enter;
//SendBufferstr += "Content-Type: application/octet-stream"+enter;
SendBufferstr += "Content-Type: text/plain;"+enter;
SendBufferstr += " name=\"=?"+Charset.ToUpper()+"?B?"+Base64Encode(filepath.Substring(filepath.LastIndexOf("\\")+1))+"?=\""+enter;
SendBufferstr += "Content-Transfer-Encoding: base64"+enter;
SendBufferstr += "Content-Disposition: attachment;"+enter;
SendBufferstr += " filename=\"=?"+Charset.ToUpper()+"?B?"+Base64Encode(filepath.Substring(filepath.LastIndexOf("\\")+1))+"?=\""+enter+enter;
SendBufferstr += GetStream(filepath)+enter+enter;
}
SendBufferstr += "--====="+ (this._html?"001_Dragon520636771063_":"001_Dragon303406132050_") +"=====--"+enter+enter;
}
SendBufferstr += enter + "." + enter; if(!Dialog(SendBufferstr, "Error Mail"))
return false;
SendBufferstr = "QUIT" + enter;
if(!Dialog(SendBufferstr, "Quit error"))
return false;
ns.Close();
tc.Close();
return true;
}
#endregion
}}