Пример #1
0
        private static MimeMessage CreateMimeMessage(MailConfig config)
        {
            MimeMessage mimeMessage     = new MimeMessage();
            var         fromMailAddress = new MailboxAddress(config.FromName ?? config.FromAddress, config.FromAddress);

            mimeMessage.From.Add(fromMailAddress);
            for (int i = 0; i < config.ToAddress.Count; i++)
            {
                var item          = config.ToAddress[i];
                var toMailAddress = new MailboxAddress(item);
                mimeMessage.To.Add(toMailAddress);
            }
            BodyBuilder bodyBuilder = new BodyBuilder()
            {
                HtmlBody = config.Body,
            };

            if (config.Attachments != null)
            {
                var attachment = bodyBuilder.Attachments.Add(config.FileName, config.Attachments);
                //解决中文文件名乱码
                var charset = "GB18030";
                attachment.ContentType.Parameters.Clear();
                attachment.ContentDisposition.Parameters.Clear();
                attachment.ContentType.Parameters.Add(charset, "name", config.FileName);
                //解决文件名不能超过41字符
                foreach (var param in attachment.ContentType.Parameters)
                {
                    param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
                }
            }
            mimeMessage.Body    = bodyBuilder.ToMessageBody();
            mimeMessage.Subject = config.Subject;
            return(mimeMessage);
        }
Пример #2
0
        public static async Task <bool> SentAsync(MailConfig config)
        {
            try
            {
                var message = CreateMimeMessage(config);
                using (SmtpClient client = new SmtpClient())
                {
                    client.CheckCertificateRevocation          = false;
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Timeout = 10 * 1000;
                    await client.ConnectAsync(config.Host, config.Port, SecureSocketOptions.Auto);

                    await client.AuthenticateAsync(config.FromAddress, config.Password);

                    await client.SendAsync(message);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }