コード例 #1
0
ファイル: SmtpService.cs プロジェクト: netwavebe/OrchardCore
        private MimeMessage FromMailMessage(MailMessage message)
        {
            var submitterAddress = String.IsNullOrWhiteSpace(message.Sender)
                ? _options.DefaultSender
                : message.Sender;

            var mimeMessage = new MimeMessage();

            if (!String.IsNullOrEmpty(submitterAddress))
            {
                mimeMessage.Sender = MailboxAddress.Parse(submitterAddress);
            }

            if (!string.IsNullOrWhiteSpace(message.From))
            {
                foreach (var address in message.From.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.From.Add(MailboxAddress.Parse(address));
                }
            }

            if (!string.IsNullOrWhiteSpace(message.To))
            {
                foreach (var address in message.To.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.To.Add(MailboxAddress.Parse(address));
                }
            }

            if (!string.IsNullOrWhiteSpace(message.Cc))
            {
                foreach (var address in message.Cc.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.Cc.Add(MailboxAddress.Parse(address));
                }
            }

            if (!string.IsNullOrWhiteSpace(message.Bcc))
            {
                foreach (var address in message.Bcc.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.Bcc.Add(MailboxAddress.Parse(address));
                }
            }

            if (string.IsNullOrWhiteSpace(message.ReplyTo))
            {
                foreach (var address in mimeMessage.From)
                {
                    mimeMessage.ReplyTo.Add(address);
                }
            }
            else
            {
                foreach (var address in message.ReplyTo.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries))
                {
                    mimeMessage.ReplyTo.Add(MailboxAddress.Parse(address));
                }
            }

            mimeMessage.Subject = message.Subject;

            var body = new BodyBuilder();

            if (message.IsBodyHtml)
            {
                body.HtmlBody = message.Body;
            }

            if (message.IsBodyText)
            {
                body.TextBody = message.BodyText;
            }

            foreach (var attachment in message.Attachments)
            {
                // Stream must not be null, otherwise it would try to get the filesystem path
                if (attachment.Stream != null)
                {
                    body.Attachments.Add(attachment.Filename, attachment.Stream);
                }
            }

            mimeMessage.Body = body.ToMessageBody();

            return(mimeMessage);
        }
コード例 #2
0
        public async Task SendEmailAsync(
            SmtpOptions smtpOptions,
            string to,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage,
            string replyTo = null)
        {
            if (string.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentException("no to address provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml      = !string.IsNullOrWhiteSpace(htmlMessage);

            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();

            m.From.Add(new MailboxAddress("", from));
            if (!string.IsNullOrWhiteSpace(replyTo))
            {
                m.ReplyTo.Add(new MailboxAddress("", replyTo));
            }
            m.To.Add(new MailboxAddress("", to));
            m.Subject = subject;

            //m.Importance = MessageImportance.Normal;
            //Header h = new Header(HeaderId.Precedence, "Bulk");
            //m.Headers.Add()

            BodyBuilder bodyBuilder = new BodyBuilder();

            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //client.ServerCertificateValidationCallback = delegate (
                //    Object obj, X509Certificate certificate, X509Chain chain,
                //    SslPolicyErrors errors)
                //{
                //    return (true);
                //};

                await client.ConnectAsync(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl)
                .ConfigureAwait(false);

                //await client.ConnectAsync(smtpOptions.Server, smtpOptions.Port, SecureSocketOptions.StartTls);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(smtpOptions.User, smtpOptions.Password)
                    .ConfigureAwait(false);
                }

                await client.SendAsync(m).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
コード例 #3
0
ファイル: EmailService.cs プロジェクト: sindhuvv/Legecy
        async Task IEmailService.SendEmail()
        {
            try
            {
                var listEmail = await _unitOfWork.EmailQueueRepository.ListAllAsync();

                var emailAttachments = await _unitOfWork.EmailAttachmentRepository.ListAllAsync();

                string SmtpServer = "smtpout.us.kworld.kpmg.com";
                foreach (var email in listEmail)
                {
                    var message = new MimeMessage();
                    var builder = new BodyBuilder();
                    foreach (var item in email.ToList.FromDelimited(";"))
                    {
                        message.To.Add(new MailboxAddress(item));
                    }

                    foreach (var item in email.BCCList.FromDelimited(";"))
                    {
                        message.Bcc.Add(new MailboxAddress(item));
                    }

                    foreach (var item in email.CCList.FromDelimited(";"))
                    {
                        message.Cc.Add(new MailboxAddress(item));
                    }

                    message.From.Add(new MailboxAddress(email.FromAddress));
                    message.Subject = email.Subject;

                    var attachments = emailAttachments.ToList().Where(x => x.EmailQueueId == email.Id);
                    if (attachments.Any())
                    {
                        foreach (var attachment in attachments)
                        {
                            builder.Attachments.Add(attachment.Filename, attachment.FileContents);
                        }
                    }
                    var filepath = email.EmailType.Split(".");
                    var viewName = filepath[filepath.Length - 1].Replace("Model", string.Empty);
                    var type     = Type.GetType(email.EmailType);
                    var model    = JsonConvert.DeserializeObject(email.Body, type);

                    var sb = new StringBuilder();
                    sb.AppendLine("<h1>KPMG Header</h1>");
                    sb.Append(await _razorViewToStringRenderer.RenderViewToStringAsync("Email/Views/" + viewName + ".cshtml", model));
                    sb.AppendLine("KPMG Footer");
                    builder.HtmlBody = sb.ToString();
                    message.Body     = builder.ToMessageBody();

                    using (var emailClient = new SmtpClient())
                    {
                        emailClient.Connect(SmtpServer);
                        emailClient.Send(message);
                        emailClient.Disconnect(true);
                    }
                    ((IEmailService)this).DequeueEmail(email, attachments);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #4
0
        private void Send(NewletterSettings newletterSettings, string html, PlexSettings plexSettings, bool testEmail = false)
        {
            var settings = EmailSettings.GetSettings();

            if (!settings.Enabled || string.IsNullOrEmpty(settings.EmailHost))
            {
                return;
            }

            var body = new BodyBuilder {
                HtmlBody = html, TextBody = "This email is only available on devices that support HTML."
            };
            var message = new MimeMessage
            {
                Body    = body.ToMessageBody(),
                Subject = "New Content on Plex!",
            };

            if (!testEmail)
            {
                if (newletterSettings.SendToPlexUsers)
                {
                    var users = Api.GetUsers(plexSettings.PlexAuthToken);
                    foreach (var user in users.User)
                    {
                        message.Bcc.Add(new MailboxAddress(user.Username, user.Email));
                    }
                }

                if (newletterSettings.CustomUsersEmailAddresses.Any())
                {
                    foreach (var user in newletterSettings.CustomUsersEmailAddresses)
                    {
                        message.Bcc.Add(new MailboxAddress(user, user));
                    }
                }
            }
            message.Bcc.Add(new MailboxAddress(settings.EmailUsername, settings.RecipientEmail)); // Include the admin

            message.From.Add(new MailboxAddress(settings.EmailUsername, settings.EmailSender));
            try
            {
                using (var client = new SmtpClient())
                {
                    client.Connect(settings.EmailHost, settings.EmailPort); // Let MailKit figure out the correct SecureSocketOptions.

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.EmailUsername, settings.EmailPassword);
                    }
                    Log.Info("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    client.Send(message);
                    client.Disconnect(true);
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }
コード例 #5
0
ファイル: SentMail.cs プロジェクト: thaneing/WEBPAT
        public static Boolean MailSent(string server, int port, bool security, string userauten, string pwdauten, string mailsend, string mailto, string subject, string body, string mailCC)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(mailsend));
                message.Subject = subject;
                // message.To.Add(new MailboxAddress(mailto));
                // message.To.Add(new MailboxAddress(mailto2));
                string[] Multi = mailto.Split(';', ',', ':', ' ');
                foreach (var toMulti in Multi)
                {
                    //mailto = tomail + ";";
                    message.To.Add(new MailboxAddress(toMulti));
                }
                if (mailCC == "")
                {
                }
                else
                {
                    string[] MultiCC = mailCC.Split(';', ',', ':', ' ');
                    foreach (var toMultiCC in MultiCC)
                    {
                        //mailto = tomail + ";";
                        message.Cc.Add(new MailboxAddress(toMultiCC));
                    }
                }


                var bodyBuilder = new BodyBuilder();
                bodyBuilder.HtmlBody = body;

                message.Body = bodyBuilder.ToMessageBody();
                //message.Body = new TextPart("plain")
                //{
                //    //data
                //    Text = "ทดสอบบบบบบบบบบบบบบบบ"
                //};
                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    var servers   = server;
                    var ports     = port;
                    var securitys = security;

                    client.Connect(servers, ports, securitys);
                    if (securitys == false)
                    {
                    }
                    else
                    {
                        client.Authenticate(userauten, pwdauten);
                    }

                    client.Send(message);
                    client.Disconnect(true);
                    Console.WriteLine("จดหมายถูกส่งเรียบร้อยแล้ว !!");
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
コード例 #6
0
        public async Task <bool> SendEmailAsync(EmailDetailsDTO emailDetailsDTO, string to, string from,
                                                string subject, string plainTextMessage, string htmlMessage,
                                                string replyTo = null, string pdf = null)
        {
            bool hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            bool hasHtml      = !string.IsNullOrWhiteSpace(htmlMessage);
            var  message      = new MimeMessage();

            #region Argument Exceptions
            if (string.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentException("no To address provided");
            }
            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }
            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }
            if (string.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentException("no message provided");
            }
            #endregion

            message.From.Add(new MailboxAddress("", from));
            if (!string.IsNullOrWhiteSpace(replyTo))
            {
                message.ReplyTo.Add(new MailboxAddress("", replyTo));
            }
            message.To.Add(new MailboxAddress("", to));
            message.Subject = subject;


            BodyBuilder bodyBuilder = new BodyBuilder();
            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }
            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            //bodyBuilder.Attachments.Add(pdf);

            message.Body = bodyBuilder.ToMessageBody();

            try
            {
                using (SmtpClient client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    await client.ConnectAsync(
                        emailDetailsDTO.Server,
                        emailDetailsDTO.Port,
                        SecureSocketOptions.StartTlsWhenAvailable).ConfigureAwait(true);

                    // XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (emailDetailsDTO.RequiresAuthentication)
                    {
                        await client.AuthenticateAsync(emailDetailsDTO.User, emailDetailsDTO.Password)
                        .ConfigureAwait(false);
                    }
                    await client.SendAsync(message).ConfigureAwait(false);

                    await client.DisconnectAsync(true).ConfigureAwait(false);

                    return(true);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public string Send(EmailMessage emailMessage)
        {
            string NameFrom = emailMessage.FromAddresses.Substring(1, emailMessage.FromAddresses.IndexOf("/") - 1);
            string NameTo   = emailMessage.FromAddresses.Substring(1, emailMessage.FromAddresses.IndexOf("/") - 1);
            var    message  = new MimeMessage();

            try
            {
                message.From.Add(new MailboxAddress(NameFrom, emailMessage.FromAddresses));
                message.To.Add(new MailboxAddress(NameTo, emailMessage.ToAddresses));
                message.Subject = emailMessage.Subject;
                var bodyBuilder1 = new BodyBuilder();
                bodyBuilder1.HtmlBody = emailMessage.Content;


                var builder = new BodyBuilder();
                var image   = builder.LinkedResources.Add(@"./poulinalogo.png");
                image.ContentId = MimeUtils.GenerateMessageId();


                builder.HtmlBody = string.Format(@"<br><br><br>

<table>
  <thead>
    <tr>
    <td>
      {0}
      </td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>E-Mail : {1}</td>
    </tr>
    <tr>
      <td>Service : Informatique Operationnelle</td>
    </tr>
    <tr>
      <td>Poste : 801249</td>
    </tr>
    <tr>
      <td>GSM : 58278855</td>
    </tr>
</tbody>
<tfoot> 
<center><img src=""cid:{2}""></center>
</tfoot>
</table>", NameFrom, message.From.ToString(), image.ContentId);



                var multipart = new Multipart("mixed");
                multipart.Add(bodyBuilder1.ToMessageBody());
                multipart.Add(builder.ToMessageBody());


                var multipart1 = new Multipart("Attachements");
                message.Body = multipart;



                using (var emailClient = new SmtpClient())
                {
                    emailClient.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, false);

                    emailClient.Send(message);
                    emailClient.Disconnect(true);


                    EmailFrom emailFrom = new EmailFrom();

                    emailFrom.FromAddresses = emailMessage.FromAddresses;

                    emailFrom.FromName         = NameFrom;
                    emailFrom.Subject          = emailMessage.Subject;
                    emailFrom.Content          = emailMessage.Content;
                    emailFrom.SendDate         = DateTime.Now;
                    emailFrom.MessageType      = "info";
                    emailFrom.ExceptionMessage = "0";

                    _context.EmailFroms.Add(emailFrom);

                    EmailTo emailTo = new EmailTo();

                    emailTo.IdMail      = emailFrom.IdMail;
                    emailTo.Seen        = false;
                    emailTo.ToAddresses = emailMessage.ToAddresses;

                    emailTo.ToName      = NameTo;
                    emailTo.ReceiveType = "A";

                    _context.EmailTos.Add(emailTo);


                    _context.SaveChanges();
                    return("Mail success");
                }
            }
            catch (Exception ex)
            {
                EmailFrom emailFrom = new EmailFrom();

                emailFrom.FromAddresses = emailMessage.FromAddresses;

                emailFrom.FromName         = NameFrom;
                emailFrom.Subject          = emailMessage.Subject;
                emailFrom.Content          = emailMessage.Content;
                emailFrom.SendDate         = DateTime.Now;
                emailFrom.MessageType      = "info";
                emailFrom.ExceptionMessage = ex.Message;

                _context.EmailFroms.Add(emailFrom);


                EmailTo emailTo = new EmailTo();

                emailTo.IdMail      = emailFrom.IdMail;
                emailTo.Seen        = false;
                emailTo.ToAddresses = emailMessage.ToAddresses;

                emailTo.ToName      = NameTo;
                emailTo.ReceiveType = "A";
                _context.EmailTos.Add(emailTo);

                _context.SaveChanges();
                return(ex.Message);
            }
        }
コード例 #8
0
        public void SendEmail(EmailAddress recipient, string subject, string textBody, string htmlBody, List <string> attachments)
        {
            ValidationException ex = new ValidationException();

            if (recipient == null)
            {
                ex.AddError("recipientEmail", "Recipient is not specified.");
            }
            else
            {
                if (string.IsNullOrEmpty(recipient.Address))
                {
                    ex.AddError("recipientEmail", "Recipient email is not specified.");
                }
                else if (!recipient.Address.IsEmail())
                {
                    ex.AddError("recipientEmail", "Recipient email is not valid email address.");
                }
            }

            if (string.IsNullOrEmpty(subject))
            {
                ex.AddError("subject", "Subject is required.");
            }

            ex.CheckAndThrow();

            var message = new MimeMessage();

            if (!string.IsNullOrWhiteSpace(DefaultSenderName))
            {
                message.From.Add(new MailboxAddress(DefaultSenderName, DefaultSenderEmail));
            }
            else
            {
                message.From.Add(new MailboxAddress(DefaultSenderEmail, DefaultSenderEmail));
            }

            if (!string.IsNullOrWhiteSpace(recipient.Name))
            {
                message.To.Add(new MailboxAddress(recipient.Name, recipient.Address));
            }
            else
            {
                message.To.Add(new MailboxAddress(recipient.Address, recipient.Address));
            }

            if (!string.IsNullOrWhiteSpace(DefaultReplyToEmail))
            {
                message.ReplyTo.Add(new MailboxAddress(DefaultReplyToEmail, DefaultReplyToEmail));
            }

            message.Subject = subject;

            var bodyBuilder = new BodyBuilder();

            bodyBuilder.HtmlBody = htmlBody;
            bodyBuilder.TextBody = textBody;

            if (attachments != null && attachments.Count > 0)
            {
                foreach (var att in attachments)
                {
                    var filepath = att;

                    if (!filepath.StartsWith("/"))
                    {
                        filepath = "/" + filepath;
                    }

                    filepath = filepath.ToLowerInvariant();

                    if (filepath.StartsWith("/fs"))
                    {
                        filepath = filepath.Substring(3);
                    }

                    DbFileRepository fsRepository = new DbFileRepository();
                    var file  = fsRepository.Find(filepath);
                    var bytes = file.GetBytes();

                    var extension = Path.GetExtension(filepath).ToLowerInvariant();
                    new FileExtensionContentTypeProvider().Mappings.TryGetValue(extension, out string mimeType);

                    var attachment = new MimePart(mimeType)
                    {
                        Content                 = new MimeContent(new MemoryStream(bytes)),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName                = Path.GetFileName(filepath)
                    };

                    bodyBuilder.Attachments.Add(attachment);
                }
            }

            SmtpInternalService.ProcessHtmlContent(bodyBuilder);
            message.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(Server, Port, ConnectionSecurity);

                if (!string.IsNullOrWhiteSpace(Username))
                {
                    client.Authenticate(Username, Password);
                }

                client.Send(message);
                client.Disconnect(true);
            }

            Email email = new Email();

            email.Id     = Guid.NewGuid();
            email.Sender = new EmailAddress {
                Address = DefaultSenderEmail, Name = DefaultSenderName
            };
            email.ReplyToEmail = DefaultReplyToEmail;
            email.Recipients   = new List <EmailAddress> {
                recipient
            };
            email.Subject      = subject;
            email.ContentHtml  = htmlBody;
            email.ContentText  = textBody;
            email.CreatedOn    = DateTime.UtcNow;
            email.SentOn       = email.CreatedOn;
            email.Priority     = EmailPriority.Normal;
            email.Status       = EmailStatus.Sent;
            email.ServerError  = string.Empty;
            email.ScheduledOn  = null;
            email.RetriesCount = 0;
            email.ServiceId    = Id;
            if (attachments != null && attachments.Count > 0)
            {
                DbFileRepository fsRepository = new DbFileRepository();
                foreach (var att in attachments)
                {
                    var filepath = att;

                    if (!filepath.StartsWith("/"))
                    {
                        filepath = "/" + filepath;
                    }

                    filepath = filepath.ToLowerInvariant();

                    if (filepath.StartsWith("/fs"))
                    {
                        filepath = filepath.Substring(3);
                    }

                    var file = fsRepository.Find(filepath);
                    if (file == null)
                    {
                        throw new Exception($"Attachment file '{filepath}' not found.");
                    }

                    email.Attachments.Add(filepath);
                }
            }
            new SmtpInternalService().SaveEmail(email);
        }
コード例 #9
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_repository.IsThereSameEmail(model.Email))
                {
                    model.Country = _repository.GetCountries();
                    ModelState.AddModelError("Email", "Korisnik sa istom email adresom je već registrovan. ");
                    ModelState.AddModelError(string.Empty, "Korisnik sa istom email adresom je već registrovan. ");
                    return(View(model));
                }
                else
                {
                    var user = new StoreUser {
                        FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, UserName = model.Email, Address = model.Address, PostalNumber = model.PostalNumber, City = model.City, CountryId = model.CountryId, PhoneNumber = model.PhoneNumber
                    };
                    var result = await _userManager.CreateAsync(user, model.Password);

                    if (result.Succeeded)
                    {
                        var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        var confirmationLink = Url.Action("ConfirmEmail", "Account", new
                        {
                            userId = user.Id, token = token
                        }, Request.Scheme);


                        try
                        {
                            MimeMessage message = new MimeMessage();

                            MailboxAddress from = new MailboxAddress("DevitoAnonymo",
                                                                     "*****@*****.**");
                            message.From.Add(from);

                            MailboxAddress to = new MailboxAddress(model.FirstName + " " + model.LastName,
                                                                   "*****@*****.**");
                            //promeniti da stize na model.Email
                            message.To.Add(to);

                            message.Subject = "Aktivacija naloga - DevitoAnonymo.com";

                            BodyBuilder bodyBuilder = new BodyBuilder();
                            bodyBuilder.HtmlBody = "<h1>Aktivacija naloga - DevitoAnonymo.com</h1><br/>" +
                                                   "<h3>Da biste aktivirali svoj nalog, kliknite na sledeći link:</h3>" +
                                                   confirmationLink +
                                                   "<br/><hr style='width:100%'/><p><strong>Ukoliko postoji problem sa pristupom nalogu, javite se na email: [email protected]</strong></p>";

                            message.Body = bodyBuilder.ToMessageBody();

                            SmtpClient client = new SmtpClient();
                            await client.ConnectAsync("Smtp.gmail.com", 465, true);

                            await client.AuthenticateAsync("*****@*****.**", "zdmmgzjsmsiizygb");

                            await client.SendAsync(message);

                            await client.DisconnectAsync(true);

                            client.Dispose();
                        }
                        catch (Exception e)
                        {
                            throw new Exception(e.Message);
                        }

                        FlashMessage.Info("Uspešno ste registrovani. Pre nego što se prijavite, molimo vas potvrdite svoj nalog putem aktivacionog linka koji vam je poslat na email. ");
                        return(Redirect("/Account/Login"));
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            ModelState.TryAddModelError(error.Code, error.Description);
                        }

                        return(View(model));
                    }
                }
            }
            else
            {
                return(View(model));
            }
        }
コード例 #10
0
        internal void SendEmail(Email email, SmtpService service)
        {
            try
            {
                if (service == null)
                {
                    email.ServerError = "SMTP service not found";
                    email.Status      = EmailStatus.Aborted;
                    return;                     //save email in finally block will save changes
                }
                else if (!service.IsEnabled)
                {
                    email.ServerError = "SMTP service is not enabled";
                    email.Status      = EmailStatus.Aborted;
                    return;                     //save email in finally block will save changes
                }

                var message = new MimeMessage();
                if (!string.IsNullOrWhiteSpace(email.Sender?.Name))
                {
                    message.From.Add(new MailboxAddress(email.Sender?.Name, email.Sender?.Address));
                }
                else
                {
                    message.From.Add(new MailboxAddress(email.Sender?.Address, email.Sender?.Address));
                }

                foreach (var recipient in email.Recipients)
                {
                    if (recipient.Address.StartsWith("cc:"))
                    {
                        if (!string.IsNullOrWhiteSpace(recipient.Name))
                        {
                            message.Cc.Add(new MailboxAddress(recipient.Name, recipient.Address.Substring(3)));
                        }
                        else
                        {
                            message.Cc.Add(new MailboxAddress(recipient.Address.Substring(3), recipient.Address.Substring(3)));
                        }
                    }
                    else if (recipient.Address.StartsWith("bcc:"))
                    {
                        if (!string.IsNullOrWhiteSpace(recipient.Name))
                        {
                            message.Bcc.Add(new MailboxAddress(recipient.Name, recipient.Address.Substring(4)));
                        }
                        else
                        {
                            message.Bcc.Add(new MailboxAddress(recipient.Address.Substring(4), recipient.Address.Substring(4)));
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(recipient.Name))
                        {
                            message.To.Add(new MailboxAddress(recipient.Name, recipient.Address));
                        }
                        else
                        {
                            message.To.Add(new MailboxAddress(recipient.Address, recipient.Address));
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(email.ReplyToEmail))
                {
                    string[] replyToEmails = email.ReplyToEmail.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var replyEmail in replyToEmails)
                    {
                        message.ReplyTo.Add(new MailboxAddress(replyEmail, replyEmail));
                    }
                }
                else
                {
                    message.ReplyTo.Add(new MailboxAddress(email.Sender?.Address, email.Sender?.Address));
                }

                message.Subject = email.Subject;

                var bodyBuilder = new BodyBuilder();
                bodyBuilder.HtmlBody = email.ContentHtml;
                bodyBuilder.TextBody = email.ContentText;

                if (email.Attachments != null && email.Attachments.Count > 0)
                {
                    foreach (var att in email.Attachments)
                    {
                        var filepath = att;

                        if (!filepath.StartsWith("/"))
                        {
                            filepath = "/" + filepath;
                        }

                        filepath = filepath.ToLowerInvariant();

                        if (filepath.StartsWith("/fs"))
                        {
                            filepath = filepath.Substring(3);
                        }

                        DbFileRepository fsRepository = new DbFileRepository();
                        var file  = fsRepository.Find(filepath);
                        var bytes = file.GetBytes();

                        var extension = Path.GetExtension(filepath).ToLowerInvariant();
                        new FileExtensionContentTypeProvider().Mappings.TryGetValue(extension, out string mimeType);

                        var attachment = new MimePart(mimeType)
                        {
                            Content                 = new MimeContent(new MemoryStream(bytes)),
                            ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                            ContentTransferEncoding = ContentEncoding.Base64,
                            FileName                = Path.GetFileName(filepath)
                        };

                        bodyBuilder.Attachments.Add(attachment);
                    }
                }
                ProcessHtmlContent(bodyBuilder);
                message.Body = bodyBuilder.ToMessageBody();

                using (var client = new SmtpClient())
                {
                    //accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    client.Connect(service.Server, service.Port, service.ConnectionSecurity);

                    if (!string.IsNullOrWhiteSpace(service.Username))
                    {
                        client.Authenticate(service.Username, service.Password);
                    }

                    client.Send(message);
                    client.Disconnect(true);
                }
                email.SentOn      = DateTime.UtcNow;
                email.Status      = EmailStatus.Sent;
                email.ScheduledOn = null;
                email.ServerError = null;
            }
            catch (Exception ex)
            {
                email.SentOn      = null;
                email.ServerError = ex.Message;
                email.RetriesCount++;
                if (email.RetriesCount >= service.MaxRetriesCount)
                {
                    email.ScheduledOn = null;
                    email.Status      = EmailStatus.Aborted;
                }
                else
                {
                    email.ScheduledOn = DateTime.UtcNow.AddMinutes(service.RetryWaitMinutes);
                    email.Status      = EmailStatus.Pending;
                }
            }
            finally
            {
                new SmtpInternalService().SaveEmail(email);
            }
        }
コード例 #11
0
        private void SendMailMessage(string sendTo, string subject, string body)
        {
            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Joey Tribbiani", "*****@*****.**"));
                message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "*****@*****.**"));
                message.Subject = "How you doin'?";

                // message.Body = new TextPart("plain")
                // {
                //     Text = @"Hey Chandler,I just wanted to let you know that Monica and I were going to go play some paintball, you in?-- Joey"
                // };

                using (var client = new SmtpClient())
                {
                    client.Connect("smtp.sendgrid.net", 587);
                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    var bodyBuilder = new BodyBuilder();
                    bodyBuilder.HtmlBody = "<b>This is some html text</b>";
                    bodyBuilder.TextBody = "This is some plain text";

                    message.Body = bodyBuilder.ToMessageBody();

                    client.Send(message);

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate("*****@*****.**", "Ohio123!!");

                    client.Send(message);
                    client.Disconnect(true);
                }
                //     var msg = new SendGridMessage();
                //     msg.SetFrom(new EmailAddress("*****@*****.**", "SendGrid DX Team"));
                //     var recipients = new List<EmailAddress>
                //     {
                //         new EmailAddress("*****@*****.**", "Jeff Smith"),
                //         new EmailAddress("*****@*****.**", "Anna Lidman")                };
                //     msg.AddTos(recipients);
                //     msg.SetSubject("Testing the SendGrid C# Library");
                //     msg.AddContent(MimeType.Text, "Hello World plain text!");
                //     msg.AddContent(MimeType.Html, "<p>Hello World!</p>");
                // var apiKey = "AstroABC";
                // var client = new SendGridClient(apiKey);

                // MailMessage htmlMessage;
                //SmtpClient smtpClient;


                // htmlMessage = new MailMessage(_configuration["EmailSender:FromAddress"], sendTo, subject, body);
                // htmlMessage.IsBodyHtml = true;
                // smtpClient = new SmtpClient(_configuration["EmailSender:SmtpServer"]);

                // if (string.IsNullOrEmpty(_configuration["EmailSender:Password"]))
                //    smtpClient.UseDefaultCredentials = true;
                // else
                //     smtpClient.Credentials = new System.Net.NetworkCredential(_configuration["EmailSender:FromAddress"], _configuration["EmailSender:Password"]);

                //  if (Boolean.TryParse(_configuration["EmailSender:EnableSsl"], out bool enableSsl))
                //    smtpClient.EnableSsl = enableSsl;


                // _logger.LogInformation($"Sent email in context of { subject } to: \"{ sendTo }\"");
            }
            catch (Exception ex)
            {
                _logger.LogError($"Failed sending email in context of { subject } to: \"{ sendTo }\" Error: { ex.Message }");
            }
        }
コード例 #12
0
        public void EmailToAdminForNewsletterRecord(string email)
        {
            MimeMessage message  = new MimeMessage();
            MimeMessage message2 = new MimeMessage();
            MimeMessage message3 = new MimeMessage();

            MailboxAddress from = new MailboxAddress("Health Web Software",
                                                     "*****@*****.**");

            message.From.Add(from);
            message2.From.Add(from);
            message3.From.Add(from);

            MailboxAddress to = new MailboxAddress("Merhaba",
                                                   "*****@*****.**");
            MailboxAddress to2 = new MailboxAddress("Merhaba",
                                                    "*****@*****.**");
            MailboxAddress to3 = new MailboxAddress("Merhaba",
                                                    "*****@*****.**");

            message.To.Add(to);
            message2.To.Add(to2);
            message3.To.Add(to3);

            message.Subject  = "healthwebsoftware sitesi eposta aboneliğine yeni üye kaydı yapıldı";
            message2.Subject = "healthwebsoftware sitesi eposta aboneliğine yeni üye kaydı yapıldı";
            message3.Subject = "healthwebsoftware sitesi eposta aboneliğine yeni üye kaydı yapıldı";

            BodyBuilder bodyBuilder = new BodyBuilder();

            bodyBuilder.TextBody = "Healthwebsoftware sitesi eposta bülten aboneliğine yeni üye kaydı yapıldı. Yeni kayıt yapan üyenin eposta adresi: " + email + " Toplam eposta bülten abone sayısı: " + _emailNewsletterRepo.GetAllEntities().Count().ToString();

            message.Body  = bodyBuilder.ToMessageBody();
            message2.Body = bodyBuilder.ToMessageBody();
            message3.Body = bodyBuilder.ToMessageBody();

            MailKit.Net.Smtp.SmtpClient client  = new MailKit.Net.Smtp.SmtpClient();
            MailKit.Net.Smtp.SmtpClient client2 = new MailKit.Net.Smtp.SmtpClient();
            MailKit.Net.Smtp.SmtpClient client3 = new MailKit.Net.Smtp.SmtpClient();

            try
            {
                client.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client.Authenticate("*****@*****.**", "11791191");
                client.Authenticate("*****@*****.**", "UbsisCinnah2015Eylul");
                client.Send(message);
                client.Disconnect(true);
                client.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "eposta bülten aboneliği uyarı maili gönderme hatası",
                    ErrorDetail   = "eposta bülten aboneliği uyarı maili gönderme hatası"
                });
            }
            try
            {
                client2.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client2.Authenticate("*****@*****.**", "11791191");
                client2.Send(message2);
                client2.Disconnect(true);
                client2.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "eposta bülten aboneliği uyarı maili gönderme hatası",
                    ErrorDetail   = "eposta bülten aboneliği uyarı maili gönderme hatası"
                });
            }
            try
            {
                //client3.Connect("mail.misdanismanlik.com", 25, SecureSocketOptions.None);
                //client.Connect("smtp.gmail.com", 587, SecureSocketOptions.);
                //client3.Authenticate("*****@*****.**", "UbsisCinnah2015Eylul");
                client3.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client3.Authenticate("*****@*****.**", "11791191");
                client3.Send(message3);
                client3.Disconnect(true);
                client3.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "eposta bülten aboneliği uyarı maili gönderme hatası",
                    ErrorDetail   = "eposta bülten aboneliği uyarı maili gönderme hatası"
                });
            }
        }
コード例 #13
0
        public void EmailToAdminForResumeWarning(CareerDto dto)
        {
            MimeMessage message  = new MimeMessage();
            MimeMessage message2 = new MimeMessage();
            MimeMessage message3 = new MimeMessage();

            MailboxAddress from = new MailboxAddress("Health Web Software",
                                                     "*****@*****.**");

            message.From.Add(from);
            message2.From.Add(from);
            message3.From.Add(from);

            MailboxAddress to = new MailboxAddress("Merhaba",
                                                   "*****@*****.**");
            MailboxAddress to2 = new MailboxAddress("Merhaba",
                                                    "*****@*****.**");
            MailboxAddress to3 = new MailboxAddress("Merhaba",
                                                    "*****@*****.**");

            message.To.Add(to);
            message2.To.Add(to2);
            message3.To.Add(to3);

            message.Subject  = "Healthwebsoftware sitesine iş başvurusu yapıldı";
            message2.Subject = "Healthwebsoftware sitesine iş başvurusu yapıldı";
            message3.Subject = "Healthwebsoftware sitesine iş başvurusu yapıldı";

            BodyBuilder bodyBuilder = new BodyBuilder();

            bodyBuilder.TextBody = "Healthwebsoftware sitesine iş başvurusu yapıldı. Başvuru sahibi: " + dto.Name + ", Eposta Adresi: " + dto.Email + ", Başvuru yapılan pozisyon: " + dto.Position + " Dosya Adı: " + dto.Resume.FileName + " Detaylar için database'i kontrol ediniz.";

            message.Body  = bodyBuilder.ToMessageBody();
            message2.Body = bodyBuilder.ToMessageBody();
            message3.Body = bodyBuilder.ToMessageBody();

            MailKit.Net.Smtp.SmtpClient client  = new MailKit.Net.Smtp.SmtpClient();
            MailKit.Net.Smtp.SmtpClient client2 = new MailKit.Net.Smtp.SmtpClient();
            MailKit.Net.Smtp.SmtpClient client3 = new MailKit.Net.Smtp.SmtpClient();

            try
            {
                client.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client.Authenticate("*****@*****.**", "11791191");
                client.Send(message);
                client.Disconnect(true);
                client.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "iş başvurusu uyarı maili gönderme hatası",
                    ErrorDetail   = "iş başvurusu maili gönderme hatası"
                });
            }
            try
            {
                client2.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client2.Authenticate("*****@*****.**", "11791191");
                client2.Send(message2);
                client2.Disconnect(true);
                client2.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "iş başvurusu uyarı maili gönderme hatası",
                    ErrorDetail   = "iş başvurusu uyarı maili gönderme hatası"
                });
            }
            try
            {
                client3.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client3.Authenticate("*****@*****.**", "11791191");
                client3.Send(message3);
                client3.Disconnect(true);
                client3.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "iş başvurusu uyarı maili gönderme hatası",
                    ErrorDetail   = "iş başvurusu uyarı maili gönderme hatası"
                });
            }
        }
コード例 #14
0
        public void EmailToAdminForContactMessage()
        {
            MimeMessage message  = new MimeMessage();
            MimeMessage message2 = new MimeMessage();
            MimeMessage message3 = new MimeMessage();

            MailboxAddress from = new MailboxAddress("Health Web Software",
                                                     "*****@*****.**");

            message.From.Add(from);
            message2.From.Add(from);
            message3.From.Add(from);

            MailboxAddress to = new MailboxAddress("Merhaba",
                                                   "*****@*****.**");
            MailboxAddress to2 = new MailboxAddress("Merhaba",
                                                    "*****@*****.**");
            MailboxAddress to3 = new MailboxAddress("Merhaba",
                                                    "*****@*****.**");

            message.To.Add(to);
            message2.To.Add(to2);
            message3.To.Add(to3);

            message.Subject  = "Healthwebsoftware sitesine iletişim mesajı geldi";
            message2.Subject = "Healthwebsoftware sitesine iletişim mesajı geldi";
            message3.Subject = "Healthwebsoftware sitesine iletişim mesajı geldi";

            BodyBuilder bodyBuilder = new BodyBuilder();

            var contactMessage = HttpContext.Session.GetObject <ContactUsDto>("contactMessageInfo");

            HttpContext.Session.Remove("contactMessageInfo");

            bodyBuilder.TextBody = "Healthwebsoftware sitesine iletişim mesajı geldi. Gönderen: " + contactMessage.Name + "(" + contactMessage.Email + ")" + " Konu: " + contactMessage.Subject + " Mesaj: " + contactMessage.Message;

            message.Body  = bodyBuilder.ToMessageBody();
            message2.Body = bodyBuilder.ToMessageBody();
            message3.Body = bodyBuilder.ToMessageBody();

            MailKit.Net.Smtp.SmtpClient client  = new MailKit.Net.Smtp.SmtpClient();
            MailKit.Net.Smtp.SmtpClient client2 = new MailKit.Net.Smtp.SmtpClient();
            MailKit.Net.Smtp.SmtpClient client3 = new MailKit.Net.Smtp.SmtpClient();

            try
            {
                //client.Connect("mail.misdanismanlik.com", 25, SecureSocketOptions.None);
                client.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client.Authenticate("*****@*****.**", "11791191");
                client.Send(message);
                client.Disconnect(true);
                client.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "iletişim mesajı uyarı maili gönderme hatası",
                    ErrorDetail   = "iletişim mesajı uyarı maili gönderme hatası"
                });
            }
            try
            {
                client2.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client2.Authenticate("*****@*****.**", "11791191");
                client2.Send(message2);
                client2.Disconnect(true);
                client2.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "iletişim mesajı uyarı maili gönderme hatası",
                    ErrorDetail   = "iletişim mesajı uyarı maili gönderme hatası"
                });
            }

            try
            {
                client3.Connect("smtp.gmail.com", 587, SecureSocketOptions.Auto);
                client3.Authenticate("*****@*****.**", "11791191");
                client3.Send(message3);
                client3.Disconnect(true);
                client3.Dispose();
            }
            catch (Exception ex)
            {
                _errorRepo.CreateEntity(new ErrorLog
                {
                    ErrorLocation = "iletişim mesajı uyarı maili gönderme hatası",
                    ErrorDetail   = "iletişim mesajı uyarı maili gönderme hatası"
                });
            }
        }
コード例 #15
0
        /// <summary>
        /// Send one file message
        /// </summary>
        /// <param name="MSP"></param>
        /// <param name="FileName"></param>
        /// <param name="SegmentSize0"></param>
        /// <param name="SegmentCount"></param>
        /// <param name="MailAccountList"></param>
        /// <param name="AccountDst"></param>
        /// <param name="SegmentMode"></param>
        /// <param name="SegmentImageSize"></param>
        /// <param name="cancel"></param>
        public static void MailSend(ref MailSendParam MSP, string[] FileName, int SegmentSize0, int[] SegmentCount, List <MailAccount> MailAccountList, int[] AccountDst, int SegmentMode, int SegmentImageSize, CancellationTokenSource cancel)
        {
            string ConsoleInfo = CreateConsoleInfoU(MSP.FileI, MSP.FileSegmentNum, SegmentCount[MSP.FileI]);

            if (MailAccountList[MSP.AccountSrc].SmtpConnect)
            {
                ConsoleInfo = ConsoleInfo + " - gr " + (MSP.AccountSrcG + 1) + ", acc " + MSP.AccountSrc + ", thr " + MSP.ThreadNo;
            }
            else
            {
                ConsoleInfo = ConsoleInfo + " - gr " + (MSP.AccountSrcG + 1) + ", acc " + MSP.AccountSrc + ", thr " + MSP.ThreadNo + ", sl " + (MSP.SmtpClientSlot + 1);
            }
            MSP.Good = true;

            Console_WriteLine_Thr(ConsoleInfo + " - upload started ");


            string AttaInfo = InfoSeparatorS + FileName[MSP.FileI] + InfoSeparatorS + IntToHex(MSP.FileSegmentNum, SegmentCount[MSP.FileI] - 1) + InfoSeparatorS + IntToHex(SegmentCount[MSP.FileI] - 1) + InfoSeparatorS + IntToHex(MSP.FileSegmentSize - 1, SegmentSize0 - 1) + InfoSeparatorS + IntToHex(SegmentSize0 - 1) + InfoSeparatorS + Digest(MSP.SegmentBuf) + InfoSeparatorS;


            MimeMessage Msg = new MimeMessage();

            Msg.From.Add(new MailboxAddress(MailAccountList[MSP.AccountSrc].Address, MailAccountList[MSP.AccountSrc].Address));
            for (int i = 0; i < AccountDst.Length; i++)
            {
                Msg.To.Add(new MailboxAddress(MailAccountList[AccountDst[i]].Address, MailAccountList[AccountDst[i]].Address));
            }
            Msg.Subject = AttaInfo;


            BodyBuilder BB = new BodyBuilder();

            switch (SegmentMode)
            {
            default:
            {
                BB.TextBody = "Attachment";
                BB.Attachments.Add("data.bin", MSP.SegmentBuf, ContentType.Parse("application/octet-stream"));
            }
            break;

            case 1:
            case 11:
            {
                BB.TextBody = "Attachment";
                BB.Attachments.Add("data.png", ConvRaw2Img(MSP.SegmentBuf, SegmentImageSize), ContentType.Parse("image/png"));
            }
            break;

            case 2:
            case 12:
            {
                BB.TextBody = ConvRaw2Txt(MSP.SegmentBuf);
            }
            break;

            case 3:
            case 13:
            {
                BB.HtmlBody = "<img src=\"data:image/png;base64," + ConvRaw2Txt(ConvRaw2Img(MSP.SegmentBuf, SegmentImageSize).ToArray()) + "\">";
            }
            break;
            }
            Msg.Body = BB.ToMessageBody();

            try
            {
                // Check if there is set connecting before and disconnecting after message sending
                if (MailAccountList[MSP.AccountSrc].SmtpConnect)
                {
                    Console_WriteLine_Thr(ConsoleInfo + " - connecting");
                    using (SmtpClient SC = MailAccountList[MSP.AccountSrc].SmtpClient_(cancel))
                    {
                        Console_WriteLine_Thr(ConsoleInfo + " - connected");
                        Console_WriteLine_Thr(ConsoleInfo + " - sending segment");
                        SC.Send(Msg);
                        Console_WriteLine_Thr(ConsoleInfo + " - disconnecting");
                        SC.Disconnect(true, cancel.Token);
                        Console_WriteLine_Thr(ConsoleInfo + " - disconnected");
                    }
                }
                else
                {
                    bool ServerReconn = MailAccountList[MSP.AccountSrc].SmtpClient_Need_Connect(MSP.SmtpClient_[MSP.AccountSrcN, MSP.SmtpClientSlot]);
                    if (ServerReconn)
                    {
                        Console_WriteLine_Thr(ConsoleInfo + " - connecting");
                    }
                    SmtpClient SC = MailAccountList[MSP.AccountSrc].SmtpClient_Connect(MSP.SmtpClient_[MSP.AccountSrcN, MSP.SmtpClientSlot], cancel);
                    if (ServerReconn)
                    {
                        Console_WriteLine_Thr(ConsoleInfo + " - connected");
                    }
                    Console_WriteLine_Thr(ConsoleInfo + " - sending segment");
                    MSP.SmtpClient_[MSP.AccountSrcN, MSP.SmtpClientSlot] = SC;
                    SC.Send(Msg);
                }
                Console_WriteLine_Thr(ConsoleInfo + " - upload finished");
            }
            catch (Exception e)
            {
                Console_WriteLine_Thr(ConsoleInfo + " - upload error: " + ExcMsg(e));
                MSP.Good = false;
            }
            Msg = null;
            CleanUp();
        }
コード例 #16
0
        private static ResponseMailInfo LocalSendMail(RequestMailInfo requestMailInfo, EmailConfigInfo mailConfig = null)
        {
            ResponseMailInfo responseMailInfo = new ResponseMailInfo();

            try
            {
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(mailConfig.LocalMailFromName, mailConfig.LocalMailFromMail));
                IList <MailboxAddress> mailboxAddresses = new List <MailboxAddress>();
                if (string.IsNullOrWhiteSpace(requestMailInfo.ReceiveMail))
                {
                    responseMailInfo = new ResponseMailInfo
                    {
                        state   = false,
                        message = $"邮件发送失败:请填写收件人邮箱"
                    };
                    return(responseMailInfo);
                }
                if (requestMailInfo.ReceiveMail != null)
                {
                    requestMailInfo.ReceiveMail = requestMailInfo.ReceiveMail.Substring(requestMailInfo.ReceiveMail.Length - 1, 1) == ";" ? requestMailInfo.ReceiveMail.Remove(requestMailInfo.ReceiveMail.Length - 1, 1) : requestMailInfo.ReceiveMail;
                    requestMailInfo.ReceiveMail.Split(';').All(s =>
                    {
                        mailboxAddresses.Add(new MailboxAddress("", s));
                        return(true);
                    });
                }
                message.To.AddRange(mailboxAddresses);
                message.Subject = requestMailInfo.SendTitle;

                IList <MailboxAddress> ccmailboxAddresses = new List <MailboxAddress>();
                if (requestMailInfo.CCMail != null)
                {
                    requestMailInfo.CCMail = requestMailInfo.CCMail.Substring(requestMailInfo.CCMail.Length - 1, 1) == ";" ? requestMailInfo.CCMail.Remove(requestMailInfo.CCMail.Length - 1, 1) : requestMailInfo.CCMail;
                    requestMailInfo.CCMail.Split(';').All(s =>
                    {
                        ccmailboxAddresses.Add(new MailboxAddress("", s));
                        return(true);
                    });
                }
                message.Cc.AddRange(ccmailboxAddresses);

                var builder = new BodyBuilder();
                if (requestMailInfo.FormatType == FormatTypeEnum.TextBody)
                {
                    builder.TextBody = requestMailInfo.SendContent;
                }
                else if (requestMailInfo.FormatType == FormatTypeEnum.HtmlBody)
                {
                    builder.HtmlBody = requestMailInfo.SendContent;
                }

                //为了处理 中文乱码和 名称太长的问题...
                List <FileStream> list = new List <FileStream>(requestMailInfo.AttachmentList.Count());
                foreach (var path in requestMailInfo.AttachmentList)
                {
                    if (!File.Exists(path))
                    {
                        throw new FileNotFoundException("文件未找到", path);
                    }
                    var      fileName       = Path.GetFileName(path);
                    var      fileType       = MimeTypes.GetMimeType(path);
                    var      contentTypeArr = fileType.Split('/');
                    var      contentType    = new ContentType(contentTypeArr[0], contentTypeArr[1]);
                    MimePart attachment     = null;
                    var      fs             = new FileStream(path, FileMode.Open);
                    list.Add(fs);
                    attachment = new MimePart(contentType)
                    {
                        Content                 = new MimeContent(fs),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                    };
                    var charset = "GB18030";
                    attachment.ContentType.Parameters.Add(charset, "name", fileName);
                    attachment.ContentDisposition.Parameters.Add(charset, "filename", fileName);
                    foreach (var param in attachment.ContentDisposition.Parameters)
                    {
                        param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
                    }
                    foreach (var param in attachment.ContentType.Parameters)
                    {
                        param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
                    }
                    builder.Attachments.Add(attachment);
                }
                message.Body = builder.ToMessageBody();

                using (var client = new MailKit.Net.Smtp.SmtpClient())
                {
                    // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                    client.Connect(mailConfig.LocalMailSMTP, Convert.ToInt32(mailConfig.LocalMailSMTPPort), false);

                    // Note: only needed if the SMTP server requires authentication
                    client.Authenticate(mailConfig.LocalMailUserName, mailConfig.LocalMailPwd);

                    client.Send(message);
                    client.Disconnect(true);
                }
                foreach (var fs in list)
                {
                    fs.Dispose();//手动高亮
                }
                responseMailInfo = new ResponseMailInfo
                {
                    state   = true,
                    message = "发送成功"
                };
            }
            catch (Exception ex)
            {
                responseMailInfo = new ResponseMailInfo
                {
                    state   = false,
                    message = $"邮件发送失败:{ex.Message}"
                };
            }
            return(responseMailInfo);
        }
コード例 #17
0
        /// <summary>
        /// Sends the email message
        /// </summary>
        /// <param name="message">The message to send</param>
        /// <returns></returns>
        private async Task <EmailResult> SendImplAsync(EmailMessage message)
        {
            // create email message
            var email = new MimeMessage();

            // use from email or default
            var fromEmail = message.FromEmail ?? this.settings.DefaultFromEmail;

            // use from sender or default
            var fromSender = message.FromSender ?? this.settings.DefaultFromSender;

            // add from
            email.Sender = new MailboxAddress(fromSender, fromEmail);

            // add sender to from
            email.From.Add(email.Sender);

            // add to
            email.To.AddRange(message.To?.Select(MailboxAddress.Parse) ?? Enumerable.Empty <MailboxAddress>());

            // add cc
            email.Cc.AddRange(message.Cc?.Select(MailboxAddress.Parse) ?? Enumerable.Empty <MailboxAddress>());

            // add bcc
            email.Bcc.AddRange(message.Bcc?.Select(MailboxAddress.Parse) ?? Enumerable.Empty <MailboxAddress>());

            // add subject
            email.Subject = message.Subject;

            // create body builder
            var bodyBuilder = new BodyBuilder
            {
                HtmlBody = message.Body
            };

            // do for every linked resource
            message.Resources?.ForEach(resource =>
            {
                // add a resource
                var entity = (MimePart)bodyBuilder.LinkedResources.Add(resource.Path, ContentType.Parse(resource.Type));

                // assign an id for referencing
                entity.ContentId = resource.Id;

                // transfer as base64
                entity.ContentTransferEncoding = ContentEncoding.Base64;
            });

            // set body
            email.Body = bodyBuilder.ToMessageBody();

            // create new client
            using var smtp = new SmtpClient();

            // connect to server
            await smtp.ConnectAsync(this.settings.Server, this.settings.Port, ResolveEncryption(this.settings.EncryptionType));

            // authenticate in server
            await smtp.AuthenticateAsync(this.settings.Login, this.settings.Password);

            // try send an email
            await smtp.SendAsync(email);

            // try quietly disconnect
            await smtp.DisconnectAsync(true);

            // the email is sent with success
            return(new EmailResult
            {
                Sent = true
            });
        }
コード例 #18
0
ファイル: EmailService.cs プロジェクト: filenda/NETCoreSeed
        public async Task SendMultipleEmailAsync(
            string toCsv,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage)
        {
            if (string.IsNullOrWhiteSpace(toCsv))
            {
                throw new ArgumentException("no to addresses provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml      = !string.IsNullOrWhiteSpace(htmlMessage);

            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();

            m.From.Add(new MailboxAddress("", from));
            string[] adrs = toCsv.Split(',');

            foreach (string item in adrs)
            {
                if (!string.IsNullOrEmpty(item))
                {
                    m.To.Add(new MailboxAddress("", item));;
                }
            }

            m.Subject    = subject;
            m.Importance = MessageImportance.High;

            BodyBuilder bodyBuilder = new BodyBuilder();

            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl).ConfigureAwait(false);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    await client.AuthenticateAsync(
                        smtpOptions.User,
                        smtpOptions.Password).ConfigureAwait(false);
                }

                await client.SendAsync(m).ConfigureAwait(false);

                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
コード例 #19
0
ファイル: EmailSender.cs プロジェクト: grandnode/grandnode2
        /// <summary>
        /// Sends an email
        /// </summary>
        /// <param name="emailAccount">Email account to use</param>
        /// <param name="subject">Subject</param>
        /// <param name="body">Body</param>
        /// <param name="fromAddress">From address</param>
        /// <param name="fromName">From display name</param>
        /// <param name="toAddress">To address</param>
        /// <param name="toName">To display name</param>
        /// <param name="replyToAddress">ReplyTo address</param>
        /// <param name="replyToName">ReplyTo display name</param>
        /// <param name="bccAddresses">BCC addresses list</param>
        /// <param name="ccAddresses">CC addresses list</param>
        /// <param name="attachmentFilePath">Attachment file path</param>
        /// <param name="attachmentFileName">Attachment file name. If specified, then this file name will be sent to a recipient. Otherwise, "AttachmentFilePath" name will be used.</param>
        /// <param name="attachedDownloads">Attachment download ID (another attachedment)</param>
        public virtual async Task SendEmail(EmailAccount emailAccount, string subject, string body,
                                            string fromAddress, string fromName, string toAddress, string toName,
                                            string replyToAddress                  = null, string replyToName = null,
                                            IEnumerable <string> bccAddresses      = null, IEnumerable <string> ccAddresses = null,
                                            string attachmentFilePath              = null, string attachmentFileName = null,
                                            IEnumerable <string> attachedDownloads = null)

        {
            var message = new MimeMessage();

            //from, to, reply to
            message.From.Add(new MailboxAddress(fromName, fromAddress));
            message.To.Add(new MailboxAddress(toName, toAddress));
            if (!String.IsNullOrEmpty(replyToAddress))
            {
                message.ReplyTo.Add(new MailboxAddress(replyToName, replyToAddress));
            }

            //BCC
            if (bccAddresses != null && bccAddresses.Any())
            {
                foreach (var address in bccAddresses.Where(bccValue => !String.IsNullOrWhiteSpace(bccValue)))
                {
                    message.Bcc.Add(MailboxAddress.Parse(address.Trim()));
                }
            }

            //CC
            if (ccAddresses != null && ccAddresses.Any())
            {
                foreach (var address in ccAddresses.Where(ccValue => !String.IsNullOrWhiteSpace(ccValue)))
                {
                    message.Cc.Add(MailboxAddress.Parse(address.Trim()));
                }
            }

            //subject
            message.Subject = subject;

            //content
            var builder = new BodyBuilder();

            builder.HtmlBody = body;

            //create  the file attachment for this e-mail message
            if (!String.IsNullOrEmpty(attachmentFilePath) &&
                File.Exists(attachmentFilePath))
            {
                // TODO: should probably include a check for the attachmentFileName not being null or white space
                var attachment = new MimePart(_mimeMappingService.Map(attachmentFileName))
                {
                    Content            = new MimeContent(File.OpenRead(attachmentFilePath), ContentEncoding.Default),
                    ContentDisposition = new ContentDisposition(ContentDisposition.Attachment)
                    {
                        CreationDate     = File.GetCreationTime(attachmentFilePath),
                        ModificationDate = File.GetLastWriteTime(attachmentFilePath),
                        ReadDate         = File.GetLastAccessTime(attachmentFilePath)
                    },
                    ContentTransferEncoding = ContentEncoding.Base64,
                    FileName = Path.GetFileName(attachmentFilePath),
                };
                builder.Attachments.Add(attachment);
            }
            //another attachment?
            if (attachedDownloads != null)
            {
                foreach (var attachedDownloadId in attachedDownloads)
                {
                    var download = await _downloadService.GetDownloadById(attachedDownloadId);

                    if (download != null)
                    {
                        //we do not support URLs as attachments
                        if (!download.UseDownloadUrl)
                        {
                            string fileName = !String.IsNullOrWhiteSpace(download.Filename) ? download.Filename : download.Id;
                            fileName += download.Extension;
                            var ms         = new MemoryStream(download.DownloadBinary);
                            var attachment = new MimePart(download.ContentType ?? _mimeMappingService.Map(fileName))
                            {
                                Content            = new MimeContent(ms, ContentEncoding.Default),
                                ContentDisposition = new ContentDisposition(ContentDisposition.Attachment)
                                {
                                    CreationDate     = DateTime.UtcNow,
                                    ModificationDate = DateTime.UtcNow,
                                    ReadDate         = DateTime.UtcNow
                                },
                                ContentTransferEncoding = ContentEncoding.Base64,
                                FileName = fileName,
                            };
                            builder.Attachments.Add(attachment);
                        }
                    }
                }
            }
            message.Body = builder.ToMessageBody();

            //send email
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.ServerCertificateValidationCallback = (s, c, h, e) => emailAccount.UseServerCertificateValidation;
                await smtpClient.ConnectAsync(emailAccount.Host, emailAccount.Port, (SecureSocketOptions)emailAccount.SecureSocketOptionsId);

                await smtpClient.AuthenticateAsync(emailAccount.Username, emailAccount.Password);

                await smtpClient.SendAsync(message);

                await smtpClient.DisconnectAsync(true);
            }
        }
コード例 #20
0
        /// <summary>
        /// send email
        /// </summary>
        /// <param name="content">email content</param>
        /// <param name="emailSetting">email setting</param>
        /// <returns></returns>
        bool SendEmail(string content, EmailSetting emailSetting)
        {
            try
            {
                _logger.LogInformation($"send email begin");
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress(emailSetting.UserName, emailSetting.FromAddresses));
                var toaddresses = emailSetting.ToAddresses?.Split(',');
                foreach (var toaddresse in toaddresses)
                {
                    message.To.Add(new MailboxAddress(toaddresse.Split('@')?[0], toaddresse));
                }
                message.Subject = emailSetting.Subject;
                var builder = new BodyBuilder();

                builder.TextBody = emailSetting.Body;
                var encoding  = Encoding.GetEncoding(emailSetting.AttachmentEncoding);
                var inStream  = new MemoryStream(encoding.GetBytes(content ?? ""));
                var outStream = new MemoryStream();
                if (emailSetting.IsAttachment)
                {
                    if (emailSetting.IsCompress)
                    {
                        outStream = CreateToMemoryStream(inStream, emailSetting.CompressFile, emailSetting.CompressPassword);
                        builder.Attachments.Add($"{Path.GetFileNameWithoutExtension(emailSetting.CompressFile)}.zip", outStream);
                    }
                    else
                    {
                        builder.Attachments.Add($"{emailSetting.AttachmentName}", inStream);
                    }
                }
                else
                {
                    builder.TextBody += content ?? "";
                }
                message.Body = builder.ToMessageBody();
                using (var client = new SmtpClient())
                {
                    client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                    client.Connect(emailSetting.Host, emailSetting.Port, true);
                    client.AuthenticationMechanisms.Remove("XOAUTH2");
                    client.Authenticate(emailSetting.FromAddresses, emailSetting.Password);
                    client.Send(message);
                    client.Disconnect(true);
                }
                inStream.Close();
                outStream.Close();

                _logger.LogInformation($"send email  success");
                return(true);
            }
            catch (Exception exc)
            {
                _logger.LogCritical(exc, $"email send failure");
                return(false);
            }

            MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName, string compresspassword)
            {
                var outputMemStream = new MemoryStream();
                var zipStream       = new ZipOutputStream(outputMemStream);

                //0-9, 9 being the highest level of compression
                zipStream.SetLevel(3);
                if (!string.IsNullOrEmpty(compresspassword?.Trim()))
                {
                    zipStream.Password = compresspassword;
                }
                var newEntry = new ZipEntry(zipEntryName);

                newEntry.DateTime = DateTime.Now;
                zipStream.PutNextEntry(newEntry);
                var length = memStreamIn.Length < 1024 ? 1024 : memStreamIn.Length;

                StreamUtils.Copy(memStreamIn, zipStream, new byte[length]);
                zipStream.CloseEntry();
                //False stops the Close also Closing the underlying stream.
                zipStream.IsStreamOwner = false;
                //Must finish the ZipOutputStream before using outputMemStream.
                zipStream.Close();

                outputMemStream.Position = 0;
                return(outputMemStream);
            }
        }
コード例 #21
0
        private async Task SendEmailAsync(string name, string email)
        {
            /// Create a MineMessage object to setup an instance of email to be send
            MimeMessage message = new MimeMessage();

            /// Add the email settings for the sender of the email
            message.From.Add(new MailboxAddress(_EmailSettings.SenderName, _EmailSettings.Sender));

            /// Add the destination email to the message
            message.To.Add(new MailboxAddress(name, email));

            /// Add the subject of the email
            message.Subject = Template.Subject;

            /// Set the body of the email and type
            BodyBuilder bodyBuilder = new BodyBuilder()
            {
                TextBody = HtmlToPlainText(Template.HTML),
                HtmlBody = Template.HTML
            };

            /// if Email must have an attachment then add it to the multi part email
            if (_Attachment != null)
            {
                /// Open a memory stream for
                using (MemoryStream attSteam = new MemoryStream(_Attachment))
                {
                    MimePart attachment = new MimePart("application", "PDF");
                    attachment.Content                 = new MimeContent(attSteam, ContentEncoding.Default);
                    attachment.ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment);
                    attachment.ContentTransferEncoding = ContentEncoding.Base64;
                    attachment.FileName                = "Invoice";
                    bodyBuilder.Attachments.Add(attachment);
                }
            }

            /// Set the message body to the value of multi part email
            message.Body = bodyBuilder.ToMessageBody();


            async Task trySendEmail()
            {
                /// Create a disposable "SmtpClient" object in order to send the email
                using (SmtpClient client = new SmtpClient())
                {
                    /// call back method that validates the server certificate for security purposes
                    client.ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
                    {
                        /// if there are no errors in the certificate then validate the check
                        if (errors == SslPolicyErrors.None || !_EmailSettings.SslCheck)
                        {
                            return(true);
                        }
                        else if (errors.Equals(SslPolicyErrors.RemoteCertificateNameMismatch) && certificate.Subject.Equals("CN=*.a2hosting.com, O=A2 Hosting, Inc., L=Ann Arbor, S=Michigan, C=US"))
                        {
                            return(true);
                        }
                        else if (_EmailSettings.MailServer.Equals(sender))
                        {
                            return(true);
                        }

                        /// which both should be denied
                        return(false);
                    };

                    /// Try connecting to the smtp server using SSL connection
                    await client.ConnectAsync(
                        _EmailSettings.MailServer,
                        _EmailSettings.MailPort,
                        SecureSocketOptions.SslOnConnect).ConfigureAwait(false);

                    /// Pass the authentication information to the connected server to perform outgoing email request
                    await client.AuthenticateAsync(_EmailSettings.Sender, _EmailSettings.Password).ConfigureAwait(false);

                    /// use the smtp client to send the email
                    await client.SendAsync(message).ConfigureAwait(false);

                    /// disconnect the smpt client connection
                    await client.DisconnectAsync(true).ConfigureAwait(false);
                }
            }

            int timerDelayms = 1000;

            /// local method to retry sending the message 4 times if email failed to send.
            /// delay by 1000, 2000, 4000, 16000 (ms)
            async Task sendMail()
            {
                try
                {
                    await trySendEmail().ConfigureAwait(false);
                }
                catch (Exception)
                {
                    System.Threading.Thread.Sleep(timerDelayms);
                    if (timerDelayms > 16000)
                    {
                        timerDelayms = 1000;
                        throw;
                    }
                    timerDelayms *= 2;
                    await trySendEmail().ConfigureAwait(false);
                }
            }

            await sendMail().ConfigureAwait(false);
        }
コード例 #22
0
        /// <summary>
        /// This will load up the Email template and generate the HTML
        /// </summary>
        /// <param name="model"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public async Task SendAdHoc(NotificationMessage model, EmailNotificationSettings settings)
        {
            try
            {
                var email = new EmailBasicTemplate();

                var customization = await CustomizationSettings.GetSettingsAsync();

                var html = email.LoadTemplate(model.Subject, model.Message, null, customization.Logo);

                var textBody = string.Empty;

                model.Other.TryGetValue("PlainTextBody", out textBody);
                var body = new BodyBuilder
                {
                    HtmlBody = html,
                    TextBody = textBody
                };

                var message = new MimeMessage
                {
                    Body    = body.ToMessageBody(),
                    Subject = model.Subject
                };
                message.From.Add(new MailboxAddress(string.IsNullOrEmpty(settings.SenderName) ? settings.SenderAddress : settings.SenderName, settings.SenderAddress));
                message.To.Add(new MailboxAddress(model.To, model.To));

                using (var client = new SmtpClient())
                {
                    if (settings.DisableCertificateChecking)
                    {
                        // Disable validation of the certificate associated with the SMTP service
                        // Helpful when the TLS certificate is not in the certificate store of the server
                        // Does carry the risk of man in the middle snooping
                        client.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
                    }

                    if (settings.DisableTLS)
                    {
                        // Does not attempt to use either TLS or SSL
                        // Helpful when MailKit finds a TLS certificate, but it unable to use it
                        client.Connect(settings.Host, settings.Port, MailKit.Security.SecureSocketOptions.None);
                    }
                    else
                    {
                        client.Connect(settings.Host, settings.Port); // Let MailKit figure out the correct SecureSocketOptions.
                    }

                    // Note: since we don't have an OAuth2 token, disable
                    // the XOAUTH2 authentication mechanism.
                    client.AuthenticationMechanisms.Remove("XOAUTH2");

                    if (settings.Authentication)
                    {
                        client.Authenticate(settings.Username, settings.Password);
                    }
                    _log.LogDebug("sending message to {0} \r\n from: {1}\r\n Are we authenticated: {2}", message.To, message.From, client.IsAuthenticated);
                    await client.SendAsync(message);

                    await client.DisconnectAsync(true);
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Exception when attempting to send an email");
                throw;
            }
        }
コード例 #23
0
        // send the email
        private void Send()
        {
            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress("Keno San Pablo", "*****@*****.**"));

            // parse to addresses
            if (!string.IsNullOrEmpty(toField))
            {
                string[] toAddresses = toField.Split(',');
                foreach (var address in toAddresses)
                {
                    if (!address.Contains('@'))
                    {
                        continue;
                    }
                    string name = address.Split('@')[0].Trim();
                    string addr = address.Trim();
                    message.To.Add(new MailboxAddress(name, addr));
                }
            }
            // parse cc addresses
            if (!string.IsNullOrEmpty(ccField))
            {
                string[] ccAddresses = ccField.Split(',');
                foreach (var address in ccAddresses)
                {
                    if (!address.Contains('@'))
                    {
                        continue;
                    }
                    string name = address.Split('@')[0].Trim();
                    string addr = address.Trim();
                    message.Cc.Add(new MailboxAddress(name, addr));
                }
            }

            // parse bcc addresses
            if (!string.IsNullOrEmpty(bccField))
            {
                string[] bccAddresses = bccField.Split(',');
                foreach (var address in bccAddresses)
                {
                    if (!address.Contains('@'))
                    {
                        continue;
                    }
                    string name = address.Split('@')[0].Trim();
                    string addr = address.Trim();
                    message.Bcc.Add(new MailboxAddress(name, addr));
                }
            }

            message.Subject = subjectField;

            BodyBuilder builder = new BodyBuilder();

            builder.TextBody = bodyField;
            if (!string.IsNullOrEmpty(attachField))
            {
                try
                {
                    builder.Attachments.Add(attachField);
                }
                catch (Exception)
                {
                    throw;
                }
            }
            message.Body = builder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                client.Connect("smtp.gmail.com", 587);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate("ece433tester", "thisclassman");

                try
                {
                    client.Send(message);
                    // Configure the message box to be displayed
                    string           messageBoxText = "Message Sent!";
                    string           caption        = "Success";
                    MessageBoxButton button         = MessageBoxButton.OK;
                    MessageBoxImage  icon           = MessageBoxImage.Exclamation;
                    MessageBox.Show(messageBoxText, caption, button, icon);
                    CloseAction();
                }
                catch (Exception)
                {
                    throw;
                }
                client.Disconnect(true);
            }
        }
コード例 #24
0
        public async Task Start(NewsletterSettings settings, bool test)
        {
            if (!settings.Enabled)
            {
                return;
            }
            var template = await _templateRepo.GetTemplate(NotificationAgent.Email, NotificationType.Newsletter);

            if (!template.Enabled)
            {
                return;
            }

            var emailSettings = await _emailSettings.GetSettingsAsync();

            if (!ValidateConfiguration(emailSettings))
            {
                return;
            }

            try
            {
                var customization = await _customizationSettings.GetSettingsAsync();

                // Get the Content
                var plexContent   = _plex.GetAll().Include(x => x.Episodes).AsNoTracking();
                var embyContent   = _emby.GetAll().Include(x => x.Episodes).AsNoTracking();
                var lidarrContent = _lidarrAlbumRepository.GetAll().Where(x => x.FullyAvailable).AsNoTracking();

                var addedLog              = _recentlyAddedLog.GetAll();
                var addedPlexMovieLogIds  = addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Parent).Select(x => x.ContentId).ToHashSet();
                var addedEmbyMoviesLogIds = addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Parent).Select(x => x.ContentId).ToHashSet();
                var addedAlbumLogIds      = addedLog.Where(x => x.Type == RecentlyAddedType.Lidarr && x.ContentType == ContentType.Album).Select(x => x.AlbumId).ToHashSet();

                var addedPlexEpisodesLogIds =
                    addedLog.Where(x => x.Type == RecentlyAddedType.Plex && x.ContentType == ContentType.Episode);
                var addedEmbyEpisodesLogIds =
                    addedLog.Where(x => x.Type == RecentlyAddedType.Emby && x.ContentType == ContentType.Episode);


                // Filter out the ones that we haven't sent yet
                var plexContentMoviesToSend   = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie && x.HasTheMovieDb && !addedPlexMovieLogIds.Contains(StringHelper.IntParseLinq(x.TheMovieDbId)));
                var embyContentMoviesToSend   = embyContent.Where(x => x.Type == EmbyMediaType.Movie && x.HasTheMovieDb && !addedEmbyMoviesLogIds.Contains(StringHelper.IntParseLinq(x.TheMovieDbId)));
                var lidarrContentAlbumsToSend = lidarrContent.Where(x => !addedAlbumLogIds.Contains(x.ForeignAlbumId)).ToHashSet();
                _log.LogInformation("Plex Movies to send: {0}", plexContentMoviesToSend.Count());
                _log.LogInformation("Emby Movies to send: {0}", embyContentMoviesToSend.Count());
                _log.LogInformation("Albums to send: {0}", lidarrContentAlbumsToSend.Count());

                var plexEpisodesToSend =
                    FilterPlexEpisodes(_plex.GetAllEpisodes().Include(x => x.Series).Where(x => x.Series.HasTvDb).AsNoTracking(), addedPlexEpisodesLogIds);
                var embyEpisodesToSend = FilterEmbyEpisodes(_emby.GetAllEpisodes().Include(x => x.Series).Where(x => x.Series.HasTvDb).AsNoTracking(),
                                                            addedEmbyEpisodesLogIds);

                _log.LogInformation("Plex Episodes to send: {0}", plexEpisodesToSend.Count());
                _log.LogInformation("Emby Episodes to send: {0}", embyEpisodesToSend.Count());
                var plexSettings = await _plexSettings.GetSettingsAsync();

                var embySettings = await _embySettings.GetSettingsAsync();

                var body = string.Empty;
                if (test)
                {
                    var plexm  = plexContent.Where(x => x.Type == PlexMediaTypeEntity.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                    var embym  = embyContent.Where(x => x.Type == EmbyMediaType.Movie).OrderByDescending(x => x.AddedAt).Take(10);
                    var plext  = _plex.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.Series.AddedAt).Take(10).ToHashSet();
                    var embyt  = _emby.GetAllEpisodes().Include(x => x.Series).OrderByDescending(x => x.AddedAt).Take(10).ToHashSet();
                    var lidarr = lidarrContent.OrderByDescending(x => x.AddedAt).Take(10).ToHashSet();
                    body = await BuildHtml(plexm, embym, plext, embyt, lidarr, settings, embySettings, plexSettings);
                }
                else
                {
                    body = await BuildHtml(plexContentMoviesToSend, embyContentMoviesToSend, plexEpisodesToSend, embyEpisodesToSend, lidarrContentAlbumsToSend, settings, embySettings, plexSettings);

                    if (body.IsNullOrEmpty())
                    {
                        return;
                    }
                }

                if (!test)
                {
                    // Get the users to send it to
                    var users = await _userManager.GetUsersInRoleAsync(OmbiRoles.ReceivesNewsletter);

                    if (!users.Any())
                    {
                        return;
                    }

                    foreach (var emails in settings.ExternalEmails)
                    {
                        users.Add(new OmbiUser
                        {
                            UserName = emails,
                            Email    = emails
                        });
                    }

                    var messageContent = ParseTemplate(template, customization);
                    var email          = new NewsletterTemplate();

                    var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                    var bodyBuilder = new BodyBuilder
                    {
                        HtmlBody = html,
                    };

                    var message = new MimeMessage
                    {
                        Body    = bodyBuilder.ToMessageBody(),
                        Subject = messageContent.Subject
                    };

                    foreach (var user in users)
                    {
                        // Get the users to send it to
                        if (user.Email.IsNullOrEmpty())
                        {
                            continue;
                        }
                        // BCC the messages
                        message.Bcc.Add(new MailboxAddress(user.Email, user.Email));
                    }

                    // Send the email
                    await _email.Send(message, emailSettings);

                    // Now add all of this to the Recently Added log
                    var recentlyAddedLog = new HashSet <RecentlyAddedLog>();
                    foreach (var p in plexContentMoviesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt     = DateTime.Now,
                            Type        = RecentlyAddedType.Plex,
                            ContentType = ContentType.Parent,
                            ContentId   = StringHelper.IntParseLinq(p.TheMovieDbId),
                        });
                    }

                    foreach (var p in plexEpisodesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt       = DateTime.Now,
                            Type          = RecentlyAddedType.Plex,
                            ContentType   = ContentType.Episode,
                            ContentId     = StringHelper.IntParseLinq(p.Series.TvDbId),
                            EpisodeNumber = p.EpisodeNumber,
                            SeasonNumber  = p.SeasonNumber
                        });
                    }
                    foreach (var e in embyContentMoviesToSend)
                    {
                        if (e.Type == EmbyMediaType.Movie)
                        {
                            recentlyAddedLog.Add(new RecentlyAddedLog
                            {
                                AddedAt     = DateTime.Now,
                                Type        = RecentlyAddedType.Emby,
                                ContentType = ContentType.Parent,
                                ContentId   = StringHelper.IntParseLinq(e.TheMovieDbId),
                            });
                        }
                    }

                    foreach (var p in embyEpisodesToSend)
                    {
                        recentlyAddedLog.Add(new RecentlyAddedLog
                        {
                            AddedAt       = DateTime.Now,
                            Type          = RecentlyAddedType.Emby,
                            ContentType   = ContentType.Episode,
                            ContentId     = StringHelper.IntParseLinq(p.Series.TvDbId),
                            EpisodeNumber = p.EpisodeNumber,
                            SeasonNumber  = p.SeasonNumber
                        });
                    }
                    await _recentlyAddedLog.AddRange(recentlyAddedLog);
                }
                else
                {
                    var admins = await _userManager.GetUsersInRoleAsync(OmbiRoles.Admin);

                    foreach (var a in admins)
                    {
                        if (a.Email.IsNullOrEmpty())
                        {
                            continue;
                        }
                        var messageContent = ParseTemplate(template, customization);

                        var email = new NewsletterTemplate();

                        var html = email.LoadTemplate(messageContent.Subject, messageContent.Message, body, customization.Logo);

                        await _email.Send(
                            new NotificationMessage { Message = html, Subject = messageContent.Subject, To = a.Email },
                            emailSettings);
                    }
                }
            }
            catch (Exception e)
            {
                _log.LogError(e, "Error when attempting to create newsletter");
                throw;
            }
        }
コード例 #25
0
        private static MimeMessage BuildMessage(MailEnvio mail_envio)
        {
            Cuenta cuenta = mail_envio.Cuenta;
            Mail   mail   = mail_envio.Mail;

            //asigna remitente / destinatario
            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(cuenta.NombreCuenta, cuenta.Usuario));

            string[] rcpts = mail.Destinatario.Split(';');
            if (rcpts.Length == 0)
            {
                message.To.Add(new MailboxAddress(mail.Destinatario));
            }
            else
            {
                foreach (string recipient in rcpts)
                {
                    message.To.Add(new MailboxAddress(recipient));
                }
            }

            if (!string.IsNullOrWhiteSpace(mail.CC))
            {
                string[] rcptsc = mail.CC.Split(';');
                if (rcptsc.Length == 0)
                {
                    message.Cc.Add(new MailboxAddress(mail.CC));
                }
                else
                {
                    foreach (string recipient in rcptsc)
                    {
                        message.Cc.Add(new MailboxAddress(recipient));
                    }
                }
                //message.Cc.Add(new MailboxAddress(mail.CC));
            }

            if (!string.IsNullOrWhiteSpace(mail.CCO))
            {
                string[] rcptsco = mail.CCO.Split(';');
                if (rcptsco.Length == 0)
                {
                    message.Bcc.Add(new MailboxAddress(mail.CCO));
                }
                else
                {
                    foreach (string recipient in rcptsco)
                    {
                        message.Bcc.Add(new MailboxAddress(recipient));
                    }
                }
                //message.Bcc.Add(new MailboxAddress(mail.CCO));
            }
            message.Subject = mail.Asunto;

            //construye el mensaje
            var builder = new BodyBuilder();

            builder.HtmlBody = mail.Texto;
            //if (html != "") builder.HtmlBody = html;
            //else builder.TextBody = mail.Texto;
            if (mail.ListaAdjuntos != null && mail.ListaAdjuntos.Count > 0)
            {
                foreach (AdjuntoMail adjunto in mail.ListaAdjuntos.OrderBy(o => o.Orden))
                {
                    builder.Attachments.Add(adjunto.Archivo); // @"C:\Users\Joey\Documents\party.ics");
                }
            }

            //string banner = System.IO.File.ReadAllText(@"C:\Temp\Firmagenerica.html");
            if (mail.Firmar && !string.IsNullOrWhiteSpace(cuenta.Firma))
            {
                builder.HtmlBody += cuenta.Firma;
            }
            //var image = builder.LinkedResources.Add(@"C:\Temp\Firmagenerica.html");
            //image.ContentId = MimeUtils.GenerateMessageId();

            message.Body = builder.ToMessageBody();

            return(message);
        }
コード例 #26
0
ファイル: EmailSender.cs プロジェクト: Pointy-hair/EventHost
        public Task SendEmailAsync(List <string> toAddresses, string subject, string body, string fromName = null, string fromEmail = null,
                                   List <string> ccAddresses = null, List <string> bccAddresses = null, string replyTo = null)
        {
            if (string.IsNullOrEmpty(fromName))
            {
                fromName = _emailConfig.FromName;
            }

            if (string.IsNullOrEmpty(fromEmail))
            {
                fromEmail = _emailConfig.FromAddress;
            }

            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromName, fromEmail));

            if (toAddresses != null && toAddresses.Any())
            {
                foreach (var address in toAddresses)
                {
                    message.To.Add(new MailboxAddress(address));
                }
            }

            if (ccAddresses != null && ccAddresses.Any())
            {
                foreach (var address in ccAddresses)
                {
                    message.Cc.Add(new MailboxAddress(address));
                }
            }

            if (bccAddresses != null && bccAddresses.Any())
            {
                foreach (var address in bccAddresses)
                {
                    message.Bcc.Add(new MailboxAddress(address));
                }
            }

            if (!string.IsNullOrEmpty(replyTo))
            {
                message.ReplyTo.Add(new MailboxAddress(replyTo));
            }

            message.Subject = subject;

            var bodyBuilder = new BodyBuilder();

            bodyBuilder.HtmlBody = body;

            message.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(_emailConfig.Server, _emailConfig.Port, _emailConfig.UseSsl);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (!string.IsNullOrEmpty(_emailConfig.User) && !string.IsNullOrEmpty(_emailConfig.Password))
                {
                    client.Authenticate(_emailConfig.User, _emailConfig.Password);
                }

                client.Send(message);
                client.Disconnect(true);
            }

            return(Task.FromResult(0));
        }
コード例 #27
0
        public void Mail(string fromName,
                         string toName, string toAddress,
                         string subject, string body, bool isHtml = false, string[] fileAttachmentPaths = null)
        {
            fromName  = fromName ?? "";
            toName    = toName ?? "";
            toAddress = toAddress ?? "";
            subject   = subject ?? "";
            body      = body ?? "";

            if (String.IsNullOrEmpty(toAddress))
            {
                throw new Exception(String.Format(ErrorResources.EMailInvalidTo, toAddress));
            }

            string fromAddress;

            if (!String.IsNullOrEmpty(FromAddress))
            {
                fromAddress = FromAddress;
            }
            else
            {
                fromAddress = ConfigurationHelper.AppSettings <string>("Mail.FromAddress");
            }
            if (String.IsNullOrEmpty(fromAddress))
            {
                throw new Exception(String.Format(ErrorResources.EMailInvalidFrom, fromAddress));
            }

            MimeMessage message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromName, fromAddress));
            foreach (var address in toAddress.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
            {
                message.To.Add(new MailboxAddress(address));
            }
            message.Subject = subject;

            //if (isHtml)
            //{
            //    message.Body = new TextPart(TextFormat.Html)
            //    {
            //        Text = body
            //    };
            //}
            //else
            //{
            //    message.Body = new TextPart(TextFormat.Text)
            //    {
            //        Text = body
            //    };
            //}

            var builder = new BodyBuilder();

            if (isHtml)
            {
                builder.HtmlBody = body;
            }
            else
            {
                builder.TextBody = body;
            }

            if (fileAttachmentPaths != null)
            {
                foreach (string path in fileAttachmentPaths)
                {
                    builder.Attachments.Add(path);
                }
            }

            message.Body = builder.ToMessageBody();

            Mail(message);
        }
コード例 #28
0
        /// <summary>
        /// Sends the email using the given SMTP settings
        /// </summary>
        /// <returns>The email async.</returns>
        /// <param name="smtpOptions">Smtp options.</param>
        /// <param name="to">To.</param>
        /// <param name="from">From.</param>
        /// <param name="subject">Subject.</param>
        /// <param name="plainTextMessage">Plain text message.</param>
        /// <param name="htmlMessage">Html message.</param>
        /// <param name="replyTo">Reply to.</param>
        public EmailRespose SendEmail(
            SmtpOptions smtpOptions,
            List <string> to,
            string from,
            string subject,
            string plainTextMessage,
            string htmlMessage,
            string replyTo = null)
        {
            if (to.Count == 0)
            {
                throw new ArgumentException("no to address provided");
            }

            if (string.IsNullOrWhiteSpace(from))
            {
                throw new ArgumentException("no from address provided");
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentException("no subject provided");
            }

            var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage);
            var hasHtml      = !string.IsNullOrWhiteSpace(htmlMessage);

            if (!hasPlainText && !hasHtml)
            {
                throw new ArgumentException("no message provided");
            }

            var m = new MimeMessage();

            m.From.Add(new MailboxAddress("", from));
            if (!string.IsNullOrWhiteSpace(replyTo))
            {
                m.ReplyTo.Add(new MailboxAddress("", replyTo));
            }

            //set recipients
            foreach (var mailAddr in to)
            {
                m.To.Add(new MailboxAddress("", mailAddr));
            }

            m.Subject = subject;

            BodyBuilder bodyBuilder = new BodyBuilder();

            if (hasPlainText)
            {
                bodyBuilder.TextBody = plainTextMessage;
            }

            if (hasHtml)
            {
                bodyBuilder.HtmlBody = htmlMessage;
            }

            m.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                client.Connect(
                    smtpOptions.Server,
                    smtpOptions.Port,
                    smtpOptions.UseSsl);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                if (smtpOptions.RequiresAuthentication)
                {
                    client.Authenticate(smtpOptions.User, smtpOptions.Password);
                }

                client.Send(m);
                client.Disconnect(true);
            }

            return(new EmailRespose()
            {
                ResponseMessage = "Email successfully sent."
            });
        }
コード例 #29
0
        public IActionResult EnviarCorreo(int id, string correo)
        {
            var book = _context.Books.Include(x => x.Author).Include(x => x.Borrower).FirstOrDefault(x => x.BookId == id);



            if (book.Borrower == null)
            {
                return(NotFound());
            }

            LendReport LP = new LendReport();
            var        ms = LP.PrepareReport(book); //Este metodo devuelve algo, devuelve un memorystream, un memorystream es algo que en su buufer puede guardar información, documentos, fotos, archivos, cosas así.

            var doc = ms.GetBuffer();               //Aquí almacenamos el documento, recuerda que ms es un memorystream que devuelve el metodo preparereport. Los memoryStream tienen un metodo get buffer que te permiten obtener lo que ellos tienen, es decir, el documento o lo que sea que guarden, buffer está en bytes, es decir getbuffer devuelve bytes

            //Preparando el reporte


            //Retornar no email

            ///Preparando mensaje
            ///
            //Destinatario, quien lo envia y el topic
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress("CComics", "aquí debes de poner tu email"));
            message.To.Add(new MailboxAddress(correo));

            message.Subject = "Factura de compra en CCcomis";


            //Buscando el saludo xd

            var Hora = DateTime.Now.Hour;

            var Saludos = "";

            if (Hora >= 6 && Hora < 12)
            {
                Saludos = "Buenos días";
            }
            else
            {
                if (Hora >= 12 && Hora < 19)
                {
                    Saludos = "Buenas tardes";
                }
                else
                {
                    Saludos = "Buenas Noches";
                }
            }

            var builder = new BodyBuilder();

            // El cuerpo del mensaje
            builder.TextBody = Saludos + ", estimado usuario.  ¿Qué tal te va? \n" +
                               "Esta es la factura por el prestamo que ha recibido del libro \n" +
                               " ¡Gracias por elegirnos!";

            // Agregarmos aquí el documento a vendiar
            MimeKit.ContentType ct = new MimeKit.ContentType("application", "pdf");
            builder.Attachments.Add("Factura", ms.GetBuffer(), ct);

            //Agregarlos al body todo lo que la clase BodyBuilder nos permitió crear
            message.Body = builder.ToMessageBody();

            using (var client = new SmtpClient())
            {
                try
                {
                    client.Connect("smtp.gmail.com", 587, false);
                    client.Authenticate("Tu correo", "Tu contrase?A");
                    client.Send(message);
                    client.Disconnect(true);
                }
                catch (Exception)
                {
                    return(RedirectToAction(nameof(List))); // si no encuentra un gmail ni nada, entonces el enviara dnuevo a la lista, pon tu correo y tu contrase?a en los campos que correspondan
                }
            }
            return(RedirectToAction(nameof(List)));
        }
コード例 #30
0
ファイル: TnefPart.cs プロジェクト: richard2753/MimeKit
		static MimeMessage ExtractTnefMessage (TnefReader reader)
		{
			var builder = new BodyBuilder ();
			var message = new MimeMessage ();

			while (reader.ReadNextAttribute ()) {
				if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
					break;

				var prop = reader.TnefPropertyReader;

				switch (reader.AttributeTag) {
				case TnefAttributeTag.RecipientTable:
					ExtractRecipientTable (reader, message);
					break;
				case TnefAttributeTag.MapiProperties:
					ExtractMapiProperties (reader, message, builder);
					break;
				case TnefAttributeTag.DateSent:
					message.Date = prop.ReadValueAsDateTime ();
					break;
				case TnefAttributeTag.Body:
					builder.TextBody = prop.ReadValueAsString ();
					break;
				}
			}

			if (reader.AttributeLevel == TnefAttributeLevel.Attachment)
				ExtractAttachments (reader, builder);

			message.Body = builder.ToMessageBody ();

			return message;
		}
コード例 #31
0
        public void BuildScheduledEmail(string queryName, string editUrl, string recipients, int queryId)
        {
            if (string.IsNullOrEmpty(recipients))
            {
                return;
            }

            if (!_emailSenderService.TrySetDelivered(queryId))
            {
                return;
            }

            var query = _db.Queries
                        .Include(q => q.DatabaseConnection)
                        .FirstOrDefault(q => q.QueryID == queryId);

            if (query != null && query.QueryDefinition != null)
            {
                var queryDefinition = JsonConvert.DeserializeObject <dynamic>(query.QueryDefinition);
                var nodes           = JsonConvert.SerializeObject(queryDefinition.Nodes);
                var selectedNodeId  = queryDefinition.SelectedNodeId.ToString();

                var data = _dbMgr.GetData(query.DatabaseConnection, nodes, selectedNodeId, null, null);

                var attachment = _convertManager.ToExcel(data);

                var message = new MimeKit.MimeMessage();

                foreach (var email in recipients.Split(','))
                {
                    message.To.Add(new MailboxAddress(email));
                }

                message.From.Add(new MailboxAddress("QueryTree", _config.GetValue <string>("Email:SenderAddress")));
                message.Subject = string.Format("Here's your scheduled report {0}", queryName);

                // load template
                string text = System.IO.File.ReadAllText(Path.Combine(_env.WebRootPath, @"../EmailTemplates/ScheduledReport.txt"));
                string html = System.IO.File.ReadAllText(Path.Combine(_env.WebRootPath, @"../EmailTemplates/ScheduledReport.html"));

                // set up replacements
                var replacements = new Dictionary <string, string>
                {
                    { "{reportname}", queryName },
                    { "{editurl}", editUrl }
                };

                // do replacement
                foreach (var key in replacements.Keys)
                {
                    text = text.Replace(key, replacements[key]);
                    html = html.Replace(key, replacements[key]);
                }

                var builder = new BodyBuilder();

                builder.TextBody = text;
                builder.HtmlBody = html;

                using (var stream = new MemoryStream(attachment))
                {
                    var fileName = queryName == null || queryName.Length == 0 ? "report" : queryName;
                    builder.Attachments.Add(string.Format("{0}.xlsx", fileName), stream);
                }

                message.Body = builder.ToMessageBody();

                _emailSender.SendMail(message);
            }
        }