可以引用的COM組件列表,發現裡面有一個名為Microsoft CDO For Exchange 2000 Library的COM組件,就是這個,我們可以用它來連接SMTP Server,使用用戶名/密碼驗證發送郵件。
下面是實現的一個例子:
Smtp Server使用的Smtp-SRV,登陸用戶名是David Euler,發送郵箱是[email protected],發送到[email protected]/
1).資源管理器裡面,添加引用(reference),添加Microsoft CDO For Exchange 2000 Library的COM組件;
2).編輯用戶界面如上圖,依次添加FromTextBox,ToTextBox,CCTextBox,BCCTextBox,SubjectTextBox,MessageTextBox,PasswordTextBox,smtpTextBox,設置MessageTextBox的TextMode屬性為“MultiLine“, PasswordTextBox的TextMode屬性為“Password“,並添加響應提示標簽,添加發送按鈕Send。
3).輸入用戶名,密碼,smtp server之後,用戶點擊Send按鈕發送郵件,
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('"+ "郵件發送成功!" +"');</script>");
}
catch (Exception ex)
{
Response.Write("<script>alert('"+ "發送失敗:" +"');</script>");
string exMsg="UserName:"+UserName+
" Passwd:"+Password+
" Smtp:"+smtpTextBox.Text.Trim();
Response.Write("<script>alert('"+ exMsg +"');</script>");
failedLabel.Text=ex.Message.ToString();
}