private bool SendSigned(Email email)
        {
            if (email.Id == 0)
            {
                Save(email);
            }
            if (Enabled)
            {
                Smtp oMailer = new Smtp();
                try
                {
                    if (email == null)
                    {
                        throw new ArgumentException("Could not send email - email object is null!");
                    }

                    _logger.Info(this.GetType(), "Attempting to send signed email id=[{0}] to=[{1}] subject=[{2}] message=[{3}]", email.Id, email.To.ToString(), email.Subject, email.Message);

                    EmailAccount senderAccount = email.From;
                    if (senderAccount == null)
                    {
                        throw new ArgumentException("Could not send email - sender account is null!");
                    }

                    oMailer.SmtpServers.Add(senderAccount.Server, senderAccount.ServerUsername, senderAccount.ServerPassword);
                    Smime       objSmime = new Smime();
                    MailMessage m        = new MailMessage();
                    m.From = new EmailAddress(senderAccount.EmailAddress, senderAccount.DisplayName);

                    foreach (EmailContact c in email.To)
                    {
                        m.To.Add(c.EmailAddress, c.DisplayName);
                    }
                    m.Subject = email.Subject;
                    if (email.IsHtml)
                    {
                        m.BodyHtmlText = email.Message;
                    }
                    else
                    {
                        m.BodyPlainText = email.Message;
                    }
                    foreach (EmailAttachment a in email.Attachments)
                    {
                        m.Attachments.Add(a.Path, a.Name);
                    }

                    // Load certificate from the specified file.
                    Certificate signingCert = new Certificate(senderAccount.CertificateFilePath, CertFileType.Pfx, senderAccount.CertificatePassword);

                    // Sign the message.
                    MailMessage signMsg = objSmime.Sign(m, signingCert);

                    oMailer.Message = signMsg;

                    oMailer.Message.ThrowExceptions = true;
                    //set utf 8 for international chars
                    oMailer.Message.Charset = "utf-8";
                    oMailer.Message.EncodeAllHeaders(System.Text.Encoding.UTF8, HeaderEncodingOptions.None);
                    if (!oMailer.Send())
                    {
                        throw new Exception("Failed sending email...");
                    }
                    string toStr = string.Join(",", (from t in email.To select t.EmailAddress).ToArray());
                    _logger.Info("Email successfully sent by MailBee.Net to=[{0}] subject=[{1}]", toStr, email.Subject);

                    email.SendingStatus = EmailSendStatus.SENT;
                    email.SendDate      = DateTime.Now;
                    UpdateEmail(email);

                    return(true);
                }
                catch (Exception ex)
                {
                    if (email == null)
                    {
                        _logger.Error(this.GetType(), ex, "Failed sending signed email.");
                        return(false);
                    }

                    EmailAccount senderAccount       = email.From;
                    string       accountName         = senderAccount == null || senderAccount.Name == null ? "" : senderAccount.Name;
                    string       accountEmailAddress = senderAccount == null || senderAccount.EmailAddress == null ? "" : senderAccount.EmailAddress;
                    string       accountServer       = senderAccount == null || senderAccount.Server == null ? "" : senderAccount.Server;
                    int          accountPort         = senderAccount == null || senderAccount.Port == null ? 0 : senderAccount.Port;


                    string toStr = string.Join(",", (from t in email.To select t.EmailAddress).ToArray());
                    _logger.Error(this.GetType(), ex, "Failed sending signed email. emailId=[{6}] account=[{0}] from=[{1}] server=[{2}] port=[{3}] to=[{4}] subject=[{5}]", accountName, accountEmailAddress, accountServer, accountPort, toStr, email.Subject, email.Id);

                    email.FailAttempts   += 1;
                    email.FailedDate      = DateTime.Now;
                    email.FailedException = ex.ToString();
                    if (email.FailAttempts <= EmailerConfig.SuspendMailAfterAttempts)
                    {
                        email.SendingStatus = EmailSendStatus.FAILED;
                    }
                    else
                    {
                        email.SendingStatus = EmailSendStatus.SUSPENDED;
                    }
                    UpdateEmail(email);

                    return(false);
                }
                finally
                {
                    oMailer.Dispose();
                    oMailer = null;
                }
            }
            return(false);
        }
Ejemplo n.º 2
0
        private bool TryDeliverMessage(SentMailMessage message)
        {
            using (var mailClient = new Smtp())
            {
                try
                {
                    var senderAccount = FindMailAccountFor(message.From.Address);

                    if (senderAccount == null)
                    {
                        throw new ArgumentException("Could not deliver message - invalid account");
                    }

                    if (message.ReplyTo.Count() == 0 && !string.IsNullOrWhiteSpace(senderAccount.ReplyTo))
                    {
                        message.ReplyTo.Add(new MailAddress()
                        {
                            Address = senderAccount.ReplyTo
                        });
                    }

                    var server = mailClient.SmtpServers.Add(senderAccount.ServerAddress, senderAccount.ServerUsername, senderAccount.ServerPassword);
                    server.Port    = senderAccount.ServerPort;
                    server.Timeout = 60000;

                    var email = new MailBeeMessage()
                    {
                        Charset = "utf-8", ThrowExceptions = true
                    };

                    email.From = new MailBeeEmailAddress(senderAccount.SenderEmailAddress, message.From.DisplayName ?? senderAccount.SenderDisplayName);
                    message.To.ForEach(to => email.To.Add(to.Address, to.DisplayName));
                    message.ReplyTo.ForEach(to => email.ReplyTo.Add(to.Address, to.DisplayName));
                    message.CC.ForEach(cc => email.Cc.Add(cc.Address, cc.DisplayName));
                    message.BCC.ForEach(bcc => email.Bcc.Add(bcc.Address, bcc.DisplayName));

                    email.Subject       = message.Subject;
                    email.BodyPlainText = message.IsBodyHtml ? null : message.Body;
                    email.BodyHtmlText  = message.IsBodyHtml ? message.Body : null;

                    foreach (var attachment in message.Attachments)
                    {
                        if (attachment.Content != null)
                        {
                            email.Attachments.Add(attachment.Content, attachment.Name, string.Empty, attachment.ContentType, null, NewAttachmentOptions.None, MailTransferEncoding.None);
                        }
                        else if (!string.IsNullOrEmpty(attachment.Path))
                        {
                            email.Attachments.Add(attachment.Path, attachment.Name, string.Empty, attachment.ContentType, null, NewAttachmentOptions.None, MailTransferEncoding.None);
                        }
                    }

                    if (message.IsEncrypted)
                    {
                        email = new Smime().SignAndEncrypt(email, new Certificate(senderAccount.CertificateFilePath, CertFileType.Pfx, senderAccount.CertificatePassword), FindAllRecipientCertificatesFor(message));
                    }
                    else if (message.IsSigned)
                    {
                        email = new Smime().Sign(email, new Certificate(senderAccount.CertificateFilePath, CertFileType.Pfx, senderAccount.CertificatePassword));
                    }

                    email.EncodeAllHeaders(System.Text.Encoding.UTF8, HeaderEncodingOptions.None);

                    mailClient.Message = email;
                    mailClient.Send();

                    message.DeliveryStatus = DeliveryStatus.Sent;
                    message.SentOn         = DateTime.UtcNow;
                    return(true);
                }
                catch (Exception ex)
                {
                    message.FailedOn       = DateTime.UtcNow;
                    message.FailureCount  += 1;
                    message.FailureMessage = ex.ToString();
                    message.DeliveryStatus = (message.FailureCount < config.SuspendMailAfterAttempts) ? DeliveryStatus.Failed : DeliveryStatus.Suspended;
                    return(false);
                }
                finally
                {
                    db.SaveChanges();
                }
            }
        }