最近工作上需要給大量郵箱發(fā)email,每封信內容還不完全一樣.為了偷懶,研究了一下.net2.0的System.Net.Mail ,發(fā)現跟.net1.0版本有不同.
要實(shí)現smtp發(fā)信太簡(jiǎn)單了,這里不再班門(mén)弄斧,只是現在的smtp服務(wù)器本來(lái)就少,還基本都需要登陸認證,太麻煩,看了一些文章用MailMessage.Field.Add方法實(shí)現登錄認證,找了半天.net2.0中沒(méi)有該方法.(注:"大文"兄對登錄認證的問(wèn)題作了更正,為了大家閱讀方便,這里直接給出正確的方法:應該用:
SmtpClient smtpClient = new SmtpClient("xxx.xxx.xxx.xxx");
smtpClient.Credentials = new NetworkCredential("account", "password");
smtpClient.Timeout = 100;
smtpClient.EnableSsl = false;
)要通過(guò)網(wǎng)上的公開(kāi)smtp服務(wù)器發(fā)郵件是不可能了.(其實(shí)是可以的,只是較慢)
于是考慮通過(guò)本地smtp服務(wù)器來(lái)群發(fā),還是想偷懶,找了幾個(gè)免費的smtp本地服務(wù)器軟件.其中magic winmail4.2和musemail server2.0兩個(gè)軟件順利通過(guò)測試,前者不需要作任何配置,安裝完畢就可以用SmtpClient.Send方法發(fā)送郵件,記住要把Host設成本地主機127.0.0.1 .美中不足是只能30天試用期,后者需要簡(jiǎn)單的配置(勾掉"強制進(jìn)行SMTP發(fā)信認證",并將SMTP綁定到127.0.0.1),但是沒(méi)有時(shí)間限制.
以下提供了關(guān)鍵代碼.
private bool sendMail(string add, string from,string subject,string content, string attachmentadd)
{
try
{
MailMessage message = new MailMessage(from,add);
if (attachmentadd != "")
{
Attachment attachment = new Attachment(attachmentadd);
message.Attachments.Add(attachment);
}
if (content != "")
{
message.BodyEncoding = Encoding.GetEncoding("GBK");
message.Body = content;
}
if (subject != "")
{
message.Subject = subject;
}
SmtpClient sc = new SmtpClient("127.0.0.1",25);
sc.Send(message);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return false;
}
return true;
}
軟件編出來(lái)后遇到了一個(gè)問(wèn)題,就是中文主題再一些郵箱(如eyou)中顯示為亂碼,且無(wú)法通過(guò)設置Encoding來(lái)解決.還有一些郵箱發(fā)送后無(wú)法收到(qianlong,tom)各位大俠幫幫忙




在.net 2.0中用以下代碼就可以了。
MailMessage mlMsg = new MailMessage();
mlMsg.From = new MailAddress("from@mail.com", "fromName");
mlMsg.To.Add(new MailAddress("to@mail.com"));
mlMsg.Subject = "Title";
mlMsg.Body = "Test Mail";
mlMsg.IsBodyHtml = false;
SmtpClient smtpClient = new SmtpClient("xxx.xxx.xxx.xxx");
smtpClient.Credentials = new NetworkCredential("account", "password");
smtpClient.Timeout = 100;
smtpClient.EnableSsl = false;
smtpClient.Send(mlMsg);