csharp 用C#编写的简单SMTP邮件客户端助手类,用于异步发送电子邮件。注意:使用Log4Net进行日志记录。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 用C#编写的简单SMTP邮件客户端助手类,用于异步发送电子邮件。注意:使用Log4Net进行日志记录。相关的知识,希望对你有一定的参考价值。

using log4net;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Configuration;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading.Tasks;
using System.Web;

namespace MyApp.Helpers
{
    public static class WebMail
    {
        private static ILog _logger = LogManager.GetLogger(typeof(WebMail));

        /// <summary>
        /// Asynchronous Send Mail Helper Method
        /// </summary>
        /// <param name="toAddress">Single or comma-separated list of Email  Addresses.</param>
        /// <param name="subject">Subject Line</param>
        /// <param name="bodyText">Body Text</param>
        /// <param name="attachmentFilePath">Path to File Attachment</param>
        /// <returns>Boolean Value indicating success.<remarks>NOTE: Does not indicate Email Received, just Email Sent successfully.</remarks></returns>
        public static async Task<bool> Send(string toAddress, string subject, string bodyText, string attachmentFilePath = null)
        {
            try
            {
                MailMessage message = new MailMessage();

                // Set Message FROM Address
                SmtpSection mailSettings = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

                message.From = new MailAddress(mailSettings.From);

                if (toAddress.Contains(","))
                {
                    // Add Email Group Address List
                    message.To.Add(toAddress);
                }
                else
                {
                    // Add Single To Address
                    message.To.Add(new MailAddress(toAddress));
                }

                // Set Email Subject
                message.Subject = subject;

                // Check for and handle HTML based Email Body Text
                if (bodyText.IsHtml())
                {
                    message.IsBodyHtml = true;

                    // Strip out HTML Tags for Plain Text View
                    string plainTextBody = HtmlHelper.RemoveHtmlTags(bodyText);

                    // Create both Plain Text and HTML Alternate Views to be kind to all Email Clients
                    AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainTextBody, System.Text.Encoding.UTF8, "text/plain");
                    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(bodyText, new ContentType("text/html"));

                    // Add Alternate Views
                    message.AlternateViews.Add(plainView);
                    message.AlternateViews.Add(htmlView);
                }
                else
                {
                    message.IsBodyHtml = true;

                    // Create both Plain Text and HTML Alternate Views to be kind to all Email Clients
                    AlternateView plainView = AlternateView.CreateAlternateViewFromString(bodyText, System.Text.Encoding.UTF8, "text/plain");
                    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(bodyText.ToHtml(), new ContentType("text/html"));

                    // Add Alternate Views
                    message.AlternateViews.Add(plainView);
                    message.AlternateViews.Add(htmlView);
                }

                // If Email Attachment provided, add to Message
                if (attachmentFilePath != null)
                {
                    // Add Attachment
                    message.Attachments.Add(new Attachment(attachmentFilePath));
                }

                // Send Email Asynchronously and return Success Response
                using (var smtpClient = new SmtpClient(mailSettings.Network.Host, mailSettings.Network.Port))
                {
                    await smtpClient.SendMailAsync(message);
                }

                return true;
            }
            catch(Exception ex)
            {
                // Log Exception and return Failure Response
                _logger.Error("An error occured while attempting to send the requested Email to '" + toAddress + "'.", ex);

                return false;
            }
        }
    }
}

以上是关于csharp 用C#编写的简单SMTP邮件客户端助手类,用于异步发送电子邮件。注意:使用Log4Net进行日志记录。的主要内容,如果未能解决你的问题,请参考以下文章

深入理解SMTP协议之邮件客户端

Windows Phone 8 的 C# IMAP SMTP 邮件客户端

电子邮件如何从 SMTP 传输到 IMAP?

一个简单的本地 SMTP 服务器 [关闭]

用python 发送一个smtp邮件

smtp