Exemplo n.º 1
0
        /// <summary>
        /// SMTP邮件Sender的类的封装
        /// </summary>
        /// <param name="smtpServer">smtp服务地址</param>
        /// <param name="port">端口号</param>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="enableSSL">是否采用ssl的方式</param>
        public override bool Send(string smtpServer, int port, string userName, string password, bool enableSSL)
        {
            bool isSended = false;

            try
            {
                MailMessage message = new MailMessage();
                To.ForEach(email =>
                {
                    if (email.IsValidEmail())
                    {
                        message.To.Add(email);
                    }
                });
                message.Sender = new MailAddress(userName, userName);
                if (CC != null && CC.Any())
                {
                    CC.ForEach(email =>
                    {
                        if (email.IsValidEmail())
                        {
                            message.CC.Add(email);
                        }
                    });
                }
                message.Subject = Encoding.Default.GetString(Encoding.Default.GetBytes(Subject));

                message.From = DisplayName.IsBlank() ? new MailAddress(From) : new MailAddress(From, Encoding.Default.GetString(Encoding.Default.GetBytes(DisplayName)));

                message.Body                        = Encoding.Default.GetString(Encoding.Default.GetBytes(Body));
                message.BodyEncoding                = Encoding.GetEncoding("GBK");
                message.HeadersEncoding             = Encoding.UTF8;
                message.SubjectEncoding             = Encoding.UTF8;
                message.IsBodyHtml                  = true;
                message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                message.ReplyToList.Add(new MailAddress(From));

                SmtpClient smtp = new SmtpClient(smtpServer, port)
                {
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(userName, password),
                    Timeout   = 30000,
                    EnableSsl = enableSSL
                };

                smtp.SendCompleted += smtp_SendCompleted;
                smtp.Send(message);
                isSended = true;
            }
            catch (Exception ex)
            {
                Logger.Log("邮件发送失败:", ex);
            }
            return(isSended);
        }
Exemplo n.º 2
0
        public MailMessage Build()
        {
            MailMessage mailMessage = new MailMessage();

            if (From == null || string.IsNullOrWhiteSpace(From.Address))
            {
                throw new ArgumentException(nameof(From));
            }
            else
            {
                mailMessage.From = From;
            }

            if (To != null && To.Any())
            {
                mailMessage.To.AddRange(To);
            }

            if (CC != null && CC.Any())
            {
                mailMessage.CC.AddRange(CC);
            }

            if (Bcc != null && Bcc.Any())
            {
                mailMessage.Bcc.AddRange(Bcc);
            }

            if (!string.IsNullOrWhiteSpace(Subject))
            {
                mailMessage.Subject = Subject;
            }

            if (!string.IsNullOrWhiteSpace(Body))
            {
                mailMessage.Body       = Body;
                mailMessage.IsBodyHtml = IsBodyHtml;
            }

            if (Attachments != null && Attachments.Any())
            {
                mailMessage.Attachments.AddRange(Attachments);
            }

            return(mailMessage);
        }
        public void Validate()
        {
            if (this.Settings == null)
            {
                throw new Exception("Settings must be supplied");
            }

            this.Settings.Validate();
            this.CleanCollections();

            if (To?.Any() == false && CC?.Any() == false && BCC?.Any() == false)
            {
                throw new Exception("At lest one To, CC or BCC must be supplied");
            }

            if (string.IsNullOrWhiteSpace(this.Body))
            {
                throw new Exception("Body must have some content");
            }

            if (string.IsNullOrWhiteSpace(this.Subject))
            {
                throw new Exception("Subjet must be supplied");
            }

            this.Sender?.Validate();
            this.From?.Validate();
            this.To?.Validate();
            this.CC?.Validate();
            this.BCC?.Validate();
            this.ReplyToList?.Validate();
            this.Headers?.Validate();
            this.Attachments?.Validate();

            if (this.Attachments?.Sum(s => s.Content.Length) > MAXIMUM_SUM_ATTACHMENTS_SIZE)
            {
                throw new Exception($"Total size of attachments exceeds {(20971520 / 1024) / 1024}MB");
            }

            if (Headers?.Count > 0 && Headers.Select(s => s.Name.Trim()).Distinct(StringComparer.OrdinalIgnoreCase).Count() != Headers.Count)
            {
                throw new Exception("Duplicate email headers are not allowed");
            }
        }
Exemplo n.º 4
0
        public IEnumerable <ValidationResult> Validate(ValidationContext validationContext)
        {
            var validationResults = new List <ValidationResult>();

            foreach (string email in To)
            {
                ValidateEmail(validationResults, email, nameof(To), "To");
            }
            foreach (string email in CC)
            {
                ValidateEmail(validationResults, email, nameof(CC), "CC");
            }
            foreach (string email in Bcc)
            {
                ValidateEmail(validationResults, email, nameof(Bcc), "BCC");
            }
            if (!To.Any() && !CC.Any() && !Bcc.Any())
            {
                validationResults.Add(new ValidationResult("This email doesn't define a recipient.", new[] { nameof(To) }));
            }
            return(validationResults);
        }
Exemplo n.º 5
0
        public void Transmit(string subject, string messageBody)
        {
            MailMessage message = new MailMessage();

            if (!string.IsNullOrWhiteSpace(Sender))
            {
                Logger.LogInformation($"Using provider sender {Sender}");
                message.From = new MailAddress(Sender.Trim());
            }
            else
            {
                Logger.LogInformation($"Using default sender {Resources.mailSender}");
                message.From = new MailAddress(Resources.mailSender);
            }

            if (Recipient != null)
            {
                Recipient = Recipient?.TrimEnd(';');
                foreach (string _to in Recipient?.Split(';'))
                {
                    message.To.Add(new MailAddress(_to.Trim()));
                }
                Logger.LogInformation($"Recipient(s): {Recipient}");
            }
            else
            {
                Logger.LogError($"Recipient(s) not specified.");
                return;
            }

            if (CC != null && CC.Any())
            {
                Logger.LogInformation($"Adding {CC.Count} CCs");
                foreach (string _cc in CC)
                {
                    message.CC.Add(new MailAddress(_cc.Trim()));
                }
            }
            Client.Host     = Server;
            Client.Port     = Convert.ToInt32(Port);
            message.Subject = subject;

            string htmlMaster = Resources.EmailMasterTemplate;

            message.Body       = htmlMaster.Replace("{body}", messageBody);
            message.IsBodyHtml = true;

            if (Resources.mailAuthenticationNeeded == "true")
            {
                Logger.LogInformation($"Providing Mail Credentials");
                System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(Username, Password);
                Client.Credentials = credentials;
            }
            try
            {
                Logger.LogInformation($"Sending message with subject {message.Subject} to {message.To}");
                Client.Send(message);
            }
            catch (Exception ex)
            {
                Logger.LogError($"Error occurred while sending the mail: {ex.Message}");
            }
        }