.NET中通過OUTLOOK發送附件內容

最近碰到一個發送郵件附件的問題,隨便幾下來,方便以後學習。 

     string[] files = System.IO.Directory.GetFiles(@"~/UploadData" + "/" + DateTime.Now.ToString("yyyyMM"));  //獲取文件路徑 
                foreach (string file in files)  //循環文件夾裏面文件個個數
                {
                    //string extension = System.IO.Path.GetExtension(file); 文件擴展名
                      var attachmentMail = new System.Net.Mail.Attachment(@file);   
                      message.Attachments.Add(attachmentMail);
                }

    smtp.Send(message);   //發送郵件
                ret.success = true;
                ret.message = "发送成功";

CODE:

   /// <summary>
/// 发送邮件
/// </summary>
/// <param name="subject">邮件标题</param>
/// <param name="body">内容</param>
/// <param name="tos">接收者 格式 test@test.com 或 姓名:test@test.com</param>
/// <param name="ccs">抄送者 格式 test@test.com 或 姓名:test@test.com</param>
/// <param name="bccs">密送者 格式 test@test.com 或 姓名:test@test.com</param>
/// <returns></returns>
public static OA.Common.Result SendMail(string subject, string body, string[] tos, string[] ccs, string[] bccs)
{
OA.Common.Result ret = new OA.Common.Result();
/* try
{*/
var config = new SystemConfig().LoadConfig().Mail;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(config.SMTPServer, config.SMTPPort);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(config.UserName, config.Password);
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.BodyEncoding = System.Text.Encoding.UTF8;
message.SubjectEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = true;
message.From = new System.Net.Mail.MailAddress(config.From, config.NickName);
message.Subject = subject;
message.Body = body;
foreach (var to in tos)
{
var tt = to.Split(':');
if (tt.Length > 1)
{
message.To.Add(new System.Net.Mail.MailAddress(tt[1], tt[0]));
}
else
{
message.To.Add(tt[0]);
}
}
if (ccs != null)
{
foreach (var to in ccs)
{
var tt = to.Split(':');
if (tt.Length > 1)
{
message.CC.Add(new System.Net.Mail.MailAddress(tt[1], tt[0]));
}
else
{
message.CC.Add(tt[0]);
}
}
}
if (bccs != null)
{
foreach (var to in bccs)
{
var tt = to.Split(':');
if (tt.Length > 1)
{
message.Bcc.Add(new System.Net.Mail.MailAddress(tt[1], tt[0]));
}
else
{
message.Bcc.Add(tt[0]);
}
}
} //--发送邮件附件--
string[] files = System.IO.Directory.GetFiles(@"~/UploadData" + "/" + DateTime.Now.ToString("yyyyMM"));
foreach (string file in files)
{
//string extension = System.IO.Path.GetExtension(file);
var attachmentMail = new System.Net.Mail.Attachment(@file);
message.Attachments.Add(attachmentMail);
}
//--the end-- smtp.Send(message);
ret.success = true;
ret.message = "发送成功";
/*
}
catch(Exception e)
{
throw e;
ret.success = false;
ret.message = e.Message;
}*/
return ret;
}
上一篇:latex列表


下一篇:three.js入门2