发现公司经常会有发送邮件的功能,自己以前写的貌似都不够完整,怎么写的也忘了,每次要写还是得从网上找,这次的代码同事写的,比较全,先记下来。。。同时也方便一下其他有需要的人
try
{
// create message
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
System.Net.Mail.SmtpClient client;
// set the subject & body
message.Subject = vSubject;
message.IsBodyHtml = vHTML;
message.Body = vBodyText;
message.BodyEncoding = System.Text.Encoding.GetEncoding(vEncoding);
client = new System.Net.Mail.SmtpClient(vEmailHost);
client.Port = (vPort == 0 ? 25 : vPort);
client.EnableSsl = vEnableSSL;
if (string.IsNullOrEmpty(vEmailLoginUser))
{
client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.Timeout = 500;
}
else
{
client.Credentials = new System.Net.NetworkCredential(vEmailLoginUser, vEmailLoginPwd);
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
}
// set sender
if (string.IsNullOrEmpty(vFrom))
{
//没有发送人邮件地址[From address is empty]
}
else
{
message.From = new System.Net.Mail.MailAddress(vFrom, vFromName);
// add a recipient
if (vTo.Length == 0)
{
//没有接收人邮件地址[To address is empty]
}
else
{
//add to
foreach (string strTo in vTo)
{
//接收人邮件地址To
message.To.Add(strTo);
}
//add an attachment
if (null != vAttachment)
{
foreach (string strAttachment in vAttachment)
{
if (null != strAttachment && "" != strAttachment.Trim())
{
//设置邮件附件
message.Attachments.Add(new System.Net.Mail.Attachment(strAttachment));
}
}
}
//添加完附件后释放附件进程
for (int msgIndex = 0; msgIndex < message.Attachments.Count; msgIndex++)
{
message.Dispose();
}
// send the message
client.Send(message);
//邮件已成功发送
blnReturn = true;
}
}
}
参考地址:http://msdn.microsoft.com/zh-cn/library/system.net.mail.attachment(v=VS.80).aspx
最后感谢同事的贡献~~~~