Exemple #1
0
        public async Task Send(EmailMessage emailMessage)
        {
            try
            {
                var mimeMsg = new MimeMessage();
                mimeMsg.From.AddRange(emailMessage.FromAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                mimeMsg.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
                mimeMsg.Subject = emailMessage.Subject;
                var builder = new BodyBuilder {
                    HtmlBody = emailMessage.Content,
                };
                if (emailMessage.Attachments != null)
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        foreach (var Attachment in emailMessage.Attachments)
                        {
                            await Attachment.CopyToAsync(memoryStream);

                            builder.Attachments.Add("file", memoryStream.ToArray());
                        }
                    }
                }

                mimeMsg.Body = new TextPart(TextFormat.Html)
                {
                    Text = emailMessage.Content
                };
                await _asyncRetryPolicy.ExecuteAsync(async() => {
                    using (var client = new SmtpClient())
                    {
                        client.Connect(_emailConfiguration.SmtpServer, _emailConfiguration.SmtpPort, false);
                        client.AuthenticationMechanisms.Remove("XOAUTH2");
                        client.Authenticate(_emailConfiguration.SmtpUsername, _emailConfiguration.SmtpPassword);
                        await client.SendAsync(mimeMsg);
                        await client.DisconnectAsync(true);
                    }
                });
            }
            catch (SocketException ex)
            {
                var errorId = ErrorID.Generate(4);
                _loggerService.Error($"EmailService{errorId}   Error Message{ ex?.Message?? ex?.InnerException?.Message}");
                throw ex;
            }
        }