.Net魔法堂:发个带附件的邮件

一、前言                          

  由于工作需要最近把邮件发送封装成WebService,现在把代码记录在此,以便日后查阅。

 

二、二话不说写代码                    



private void _SendMail(string form, string pw, string subject, string[] to, string[] cc, string body, string attachmentName, byte[] attachment)
        {
            SmtpClient client = new SmtpClient(SMTP服务地址, SMTP服务端口);
            client.UseDefaultCredentials = true;
            client.Credentials = new NetworkCredential(form, pw); // 验证信息要与邮件发送源地址一致,否则无法发送
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            MailMessage message = new MailMessage();
            message.From = new MailAddress(form);
            foreach (string toItem in to)
            {
                message.To.Add(toItem);
            }
            foreach (string ccItem in cc)
            {
                message.CC.Add(ccItem);
            }
            message.Subject = subject;
            message.SubjectEncoding = Encoding.UTF8;
            message.Body = body;
            message.BodyEncoding = Encoding.UTF8;
            message.IsBodyHtml = true;
            message.Priority = MailPriority.High;

            Stream stream = null;
            Attachment data = null;
            try
            {
                if (attachment != null && attachment.Length > 0)
                {
                    stream = new MemoryStream(attachment);
                    data = new Attachment(stream, attachmentName, System.Net.Mime.MediaTypeNames.Application.Octet);
                    message.Attachments.Add(data);
                }
                client.Send(message);
            }
            finally
            {
                if (null != stream)
                {
                    stream.Close();
                }
            }
        }

三、三种发送方式                            

  发送邮件有三种方式:

  ①. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;

  直接通过远程SMTP服务器发送邮件

  ②. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.PickupDirectoryFromIis;

  通过本机的IIS服务器的SMTP服务发送邮件(后续在研究什么配置SMTP服务器?)

  ③. client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;

  将邮件发送到本机指定目录中,再通过其他手段(如通过FTP)发送到目的地

上一篇:从订阅的邮件中收到通知,WSUS3.O已提供正式下载。以下为详细信息。


下一篇:云通讯平台Twilio收购WebRTC媒体服务器Kurento