示例#1
0
        private async Task <SendEmailResponse> SendEmailAsync(EmailParticipant sender, ICollection <EmailParticipant> to,
                                                              ICollection <EmailParticipant> cc, ICollection <EmailParticipant> bcc, string subject, string content,
                                                              bool isHtml, IEnumerable <EmailAttachment> attachments)
        {
            try
            {
                using (var client = new SmtpClient())
                {
                    client.Connect(_settings.Host, _settings.Port, _settings.IsSsl);
                    // 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
                    var username = _settings.Username;
                    var password = _settings.Password;
                    if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password))
                    {
                        client.Authenticate(username, password);
                    }

                    var message = ComposeEmail(sender, to, cc, bcc, subject, content, isHtml, attachments);
                    await client.SendAsync(message);

                    client.Disconnect(true);
                    return(new SendEmailResponse {
                        Result = ProcessResultType.Ok
                    });
                }
            }
            catch (Exception ex)
            {
                return(new SendEmailResponse {
                    Result = ex
                });
            }
        }
示例#2
0
        private static MimeMessage ComposeEmail(EmailParticipant sender, IEnumerable <EmailParticipant> to,
                                                ICollection <EmailParticipant> cc, ICollection <EmailParticipant> bcc, string subject, string content,
                                                bool isHtml = false, IEnumerable <EmailAttachment> attachments = null)
        {
            var message = new MimeMessage(
                new[] { new MailboxAddress(sender.Name, sender.EmailAddress) },
                to.Where(x => !string.IsNullOrWhiteSpace(x.EmailAddress))
                .Select(x => new MailboxAddress(x.Name, x.EmailAddress))
                .ToList(),     //key is name, value is address
                subject,
                null
                );

            if (cc != null && cc.Any())
            {
                cc.ToList()
                .ForEach(x =>
                {
                    if (!string.IsNullOrWhiteSpace(x.EmailAddress))
                    {
                        message.Cc.Add(new MailboxAddress(x.Name, x.EmailAddress));
                    }
                });     //key is name, value is address
            }
            if (bcc != null && bcc.Any())
            {
                bcc.ToList()
                .ForEach(x =>
                {
                    if (!string.IsNullOrWhiteSpace(x.EmailAddress))
                    {
                        message.Bcc.Add(new MailboxAddress(x.Name, x.EmailAddress));
                    }
                });     //key is name, value is address
            }
            var body = new TextPart(isHtml ? "html" : "plain")
            {
                Text = content
            };

            var attachmentList = attachments?.ToList();

            if (attachmentList != null && attachmentList.Any())
            {
                var multipart = new Multipart("mixed")
                {
                    body
                };
                attachmentList.ForEach(c =>
                {
                    var mimetype   = DetectFileMimeType(c.FileName);
                    var attachment = new MimePart(mimetype.Split('/')[0], mimetype.Split('/')[1])
                    {
                        ContentObject =
                            new ContentObject(File.OpenRead(c.FileName), ContentEncoding.Default),
                        ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                        ContentTransferEncoding = ContentEncoding.Base64,
                        FileName = Path.GetFileName(c.FileName)
                    };
                    multipart.Add(attachment);
                });
                message.Body = multipart;
            }
            else
            {
                message.Body = body;
            }

            return(message);
        }
示例#3
0
        public async Task <SendEmailResponse> SendEmailAsync(EmailParticipant sender, IEnumerable <EmailParticipant> to,
                                                             IEnumerable <EmailParticipant> cc, IEnumerable <EmailParticipant> bcc, int interval, string subject,
                                                             string content, bool isHtml, IEnumerable <EmailAttachment> attachments,
                                                             IProgressReporter <SendEmailProgress> progressReporter)
        {
            var attachmentList = attachments.ToList();
            var toList         = to.ToList();
            var toCount        = toList.Count;
            var ccList         = cc.ToList();
            var bccList        = bcc.ToList();

            if (_emailSettings.DumpToFilesOnly)
            {
                var filePath = Path.Combine(_emailSettings.DumpFileFolder,
                                            DateTimeOffset.UtcNow.ToString("yyyy-MM-dd HHmmss") + subject);
                var dumpContentBuilder = new StringBuilder();
                dumpContentBuilder.AppendLine(subject);
                dumpContentBuilder.AppendLine();

                if (!string.IsNullOrWhiteSpace(sender?.EmailAddress))
                {
                    dumpContentBuilder.AppendLine("From: " + sender.EmailAddress);
                }

                dumpContentBuilder.AppendLine();

                foreach (var ccItem in ccList)
                {
                    dumpContentBuilder.AppendLine("To: " + ccItem.EmailAddress);
                }

                dumpContentBuilder.AppendLine();

                dumpContentBuilder.AppendLine(content);
                File.WriteAllText(filePath, dumpContentBuilder.ToString());
                return(new SendEmailResponse().WithProcessResult(ProcessResultType.Ok));
            }

            progressReporter?.SetTotal(toCount, null, $"Sending {toCount} email(s) to SMTP server...",
                                       DateTimeOffset.UtcNow);
            if (interval <= 0) //don't need to wait, just send them all in one go
            {
                var res = await SendEmailAsync(sender, toList, ccList, bccList, subject, content, isHtml,
                                               attachmentList);

                progressReporter?.Report(toList.Count, null, $"Sent {toCount} email(s) to SMTP server.",
                                         DateTimeOffset.UtcNow);
                return(res);
            }
            else //send email at given interval
            {
                var subreslst = new List <SendEmailResponse>();
                foreach (var recipient in toList)
                {
                    var subres = await SendEmailAsync(sender,
                                                      new List <EmailParticipant> {
                        recipient
                    }, ccList, bccList, subject, content, isHtml,
                                                      attachmentList);

                    subreslst.Add(subres);
                    progressReporter?.Report(1, null,
                                             $"Sent email to SMTP server: {recipient.EmailAddress} ({recipient.Name})",
                                             DateTimeOffset.UtcNow);
                    await Task.Delay(interval);
                }
                var res = CombineMultipleSendEmailResponses(subreslst);
                return(res);
            }
        }