C#使用CDO發(fā)送郵件
2024-07-21 02:18:41
供稿:網(wǎng)友
菜鳥(niǎo)學(xué)堂:
author:david euler
date: 2004/11/18
email:[email protected]
有任何問(wèn)題,請(qǐng)與我聯(lián)系:)
一直想做實(shí)現(xiàn)一個(gè)程序,定期給自己發(fā)送郵件,或者給朋友發(fā)送郵件;比如在節(jié)日或者紀(jì)念日前若干天,發(fā)送郵件給自己提醒,或者朋友生日前夕發(fā)郵件提醒。找了很長(zhǎng)時(shí)間,都沒(méi)有找到可用的資料。
csdn上查到可以用cdo,有一篇文章說(shuō)“在reference中添加cdo for windows 2000 ”,于是在引用里面找,也沒(méi)有找到一個(gè)名字以cdo開(kāi)頭的組件,下午的時(shí)候仔細(xì)看了一下可以引用的com組件列表,發(fā)現(xiàn)里面有一個(gè)名為microsoft cdo for exchange 2000 library的com組件,就是這個(gè),我們可以用它來(lái)連接smtp server,使用用戶名/密碼驗(yàn)證發(fā)送郵件。
下面是實(shí)現(xiàn)的一個(gè)例子:
smtp server使用的smtp-srv,登陸用戶名是david euler,發(fā)送郵箱是[email protected],發(fā)送到[email protected]/
1).資源管理器里面,添加引用(reference),添加microsoft cdo for exchange 2000 library的com組件;
2).編輯用戶界面如上圖,依次添加fromtextbox,totextbox,cctextbox,bcctextbox,subjecttextbox,messagetextbox,passwordtextbox,smtptextbox,設(shè)置messagetextbox的textmode屬性為“multiline“, passwordtextbox的textmode屬性為“password“,并添加響應(yīng)提示標(biāo)簽,添加發(fā)送按鈕send。
3).輸入用戶名,密碼,smtp server之后,用戶點(diǎn)擊send按鈕發(fā)送郵件,
send 按鈕的click事件代碼如下:
cdo.message omsg = new cdo.message();
//omsg.from = fromtextbox.text ;
omsg.to = totextbox.text ;
omsg.subject = subjecttextbox.text ;
omsg.textbody = messagetextbox.text ;
omsg.cc=cctextbox.text ;
omsg.bcc=bcctextbox.text ;
string username;
string emailfrom;
string password=passwordtextbox.text.tostring().trim();
username=fromtextbox.text.trim();
emailfrom=username.replace(" ","")+"@test.com";
omsg.from=emailfrom;
cdo.iconfiguration iconfg;
adodb.fields ofields;
iconfg = omsg.configuration;
ofields = iconfg.fields;
ofields["http://schemas.microsoft.com/cdo/configuration/sendusing"].value=2;
ofields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].value=emailfrom;
ofields["http://schemas.microsoft.com/cdo/configuration/smtpuserreplyemailaddress"].value=emailfrom;
ofields["http://schemas.microsoft.com/cdo/configuration/smtpaccountname"].value=username;
ofields["http://schemas.microsoft.com/cdo/configuration/sendusername"].value=username;
ofields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].value=password;
ofields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].value=1;
ofields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].value=smtptextbox.text.trim(); //smtp.163.com
ofields.update();
try
{
omsg.send();
omsg = null;
response.write("<script>alert('"+ "郵件發(fā)送成功!" +"');</script>");
}
catch (exception ex)
{
response.write("<script>alert('"+ "發(fā)送失敗:" +"');</script>");
string exmsg="username:"+username+
" passwd:"+password+
" smtp:"+smtptextbox.text.trim();
response.write("<script>alert('"+ exmsg +"');</script>");
failedlabel.text=ex.message.tostring();
}