Пример #1
0
        /// <summary>
        /// SendEmailAsync
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <SendMailResponse> SendEmailAsync(ISendMailRequest request)
        {
            var messageResponse = new SendMailResponse();
            var messageModel    = BuildEmailMessage(request);

            try
            {
                if (string.IsNullOrWhiteSpace(_token))
                {
                    await GetAuthenticationDetailAsync();
                }

                if (_client == null)
                {
                    _client = new GraphServiceClient(new DelegateAuthenticationProvider(async requestMessage =>
                    {
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _token);
                    }));
                }


                await _client.Me.SendMail(messageModel, true).Request().PostAsync();

                messageResponse.IsSuccess = true;
            }
            catch (Exception ex)
            {
                messageResponse.ErrorMessage = ex.Message;
            }

            return(messageResponse);
        }
Пример #2
0
        /// <summary>
        /// SendEmailAsync
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <SendMailResponse> SendEmailAsync(ISendMailRequest request)
        {
            var messageResponse = new SendMailResponse();

            var             requestedServerVersion = (ExchangeVersion)_clientConfig.HostClientRequestInfo.Port;
            ExchangeService service = new ExchangeService(requestedServerVersion);

            service.Credentials = _webCrendential;
            service.Url         = new Uri(_clientConfig.HostClientRequestInfo.Host);

            EmailMessage message = new EmailMessage(service)
            {
                From    = new EmailAddress(request.FromName, request.From),
                Subject = request.Subject
            };

            message.ToRecipients.Add(request.Recipients.First());
            message.Body = request.Message;

            ExtendedPropertyDefinition customHeaders;

            foreach (var header in request.Headers)
            {
                if (header.Key.Equals("List-Unsubscribe", StringComparison.OrdinalIgnoreCase))
                {
                    customHeaders = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders,
                                                                   header.Key,
                                                                   MapiPropertyType.String);
                    var splitValues = header.Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (splitValues.Length > 1)
                    {
                        message.SetExtendedProperty(customHeaders, splitValues[0]);
                    }
                    else
                    {
                        message.SetExtendedProperty(customHeaders, header.Value);
                    }
                }
                else
                {
                    customHeaders = new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders,
                                                                   header.Key,
                                                                   MapiPropertyType.String);
                    message.SetExtendedProperty(customHeaders, header.Value);
                }
            }

            try
            {
                await message.SendAndSaveCopy();

                messageResponse.IsSuccess = true;
            }
            catch (Exception ex)
            {
                messageResponse.ErrorMessage = ex.Message;
            }

            return(messageResponse);
        }
Пример #3
0
        /// <summary>
        /// SendEmailAsync
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <SendMailResponse> SendEmailAsync(ISendMailRequest request)
        {
            var response = new SendMailResponse();

            try
            {
                if (_client == null)
                {
                    _client = new SendGridClient(_clientConfig.ApiKey);
                }

                var recipientList = request.Recipients.Select(recipient => new EmailAddress(recipient)).ToList();

                var from             = new EmailAddress(request.From, request.FromName);
                var plainTextContent = HtmlText.ConvertHtml(request.Message);
                var htmlContent      = request.Message;
                var msg = MailHelper.CreateSingleEmailToMultipleRecipients(from, recipientList, request.Subject, plainTextContent, htmlContent);
                await _client.SendEmailAsync(msg);
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
                response.IsSuccess    = false;
            }


            return(response);
        }
Пример #4
0
        /// <summary>
        /// SendEmailAsync
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <SendMailResponse> SendEmailAsync(ISendMailRequest request)
        {
            var messageResponse = new SendMailResponse();
            var messageModel    = BuildEmailMessage(request);

            try
            {
                if (string.IsNullOrWhiteSpace(_token))
                {
                    await GetAuthenticationDetailAsync();
                }
                if (_client == null)
                {
                    _client = GetGmailClient();
                }

                var result = await _client.Users.Messages.Send(messageModel, "me").ExecuteAsync();

                messageResponse.IsSuccess = true;
            }
            catch (Exception ex)
            {
                messageResponse.ErrorMessage = ex.Message;
            }

            return(messageResponse);
        }
Пример #5
0
        /// <summary>
        /// BuildEmailMessage
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private Message BuildEmailMessage(ISendMailRequest model)
        {
            Message message = new Message();

            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            mail.Subject = model.Subject;
            mail.To.Add(new System.Net.Mail.MailAddress(model.Recipients[0]));

            var htmlMimeType = new ContentType("text/html");
            var textMimeType = new ContentType("text/plain");

            // Add text/plain as an AlternativeView
            var plainText     = HtmlText.ConvertHtml(model.Message);
            var plainTextView = AlternateView.CreateAlternateViewFromString(plainText);

            plainTextView.ContentType = textMimeType;
            mail.AlternateViews.Add(plainTextView);

            // Add text/html as an AlternateView
            var htmlView = AlternateView.CreateAlternateViewFromString(model.Message);

            htmlView.ContentType = htmlMimeType;
            mail.AlternateViews.Add(htmlView);

            foreach (var header in model.Headers)
            {
                mail.Headers.Add(header.Key, header.Value);
            }

            MimeKit.MimeMessage mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);


            message.Raw = Encode(mimeMessage.ToString());

            return(message);
        }
Пример #6
0
        /// <summary>
        /// BuildEmailMessage
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private Message BuildEmailMessage(ISendMailRequest model)
        {
            var recipientList = model.Recipients.Select(recipient => new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = recipient
                }
            }).ToList();
            var email = new Message
            {
                Body = new ItemBody
                {
                    Content     = model.Message,
                    ContentType = BodyType.Html
                },
                Subject      = model.Subject,
                ToRecipients = recipientList,
            };

            var singleValues = new MessageSingleValueExtendedPropertiesCollectionPage();
            var multiValues  = new MessageMultiValueExtendedPropertiesCollectionPage();

            foreach (var header in model.Headers)
            {
                if (header.Key.Equals("List-Unsubscribe", StringComparison.OrdinalIgnoreCase))
                {
                    var splitValues = header.Value.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                    if (splitValues.Length > 1)
                    {
                        multiValues.Add(new MultiValueLegacyExtendedProperty()
                        {
                            Id = string.Concat("StringArray {00020386-0000-0000-C000-000000000046} Name ", header.Key), Value = splitValues
                        });
                    }
                    else
                    {
                        singleValues.Add(new SingleValueLegacyExtendedProperty()
                        {
                            Id = string.Concat("String {00020386-0000-0000-C000-000000000046} Name ", header.Key), Value = header.Value
                        });
                    }
                }
                else
                {
                    singleValues.Add(new SingleValueLegacyExtendedProperty()
                    {
                        Id = string.Concat("String {00020386-0000-0000-C000-000000000046} Name ", header.Key), Value = header.Value
                    });
                }
            }


            if (singleValues.Count > 0)
            {
                email.SingleValueExtendedProperties = singleValues;
            }

            if (multiValues.Count > 0)
            {
                email.MultiValueExtendedProperties = multiValues;
            }


            return(email);
        }
Пример #7
0
        /// <summary>
        /// SendEmailAsync
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public Task <SendMailResponse> SendEmailAsync(ISendMailRequest request)
        {
            var sendMailResponse = new SendMailResponse();

            var tcs = new TaskCompletionSource <SendMailResponse>();

            //track the message within the handler.
            var sendGuid = Guid.NewGuid();

            SendCompletedEventHandler handler = null;

            handler = (o, ea) =>
            {
                if (!(ea.UserState is Guid) || ((Guid)ea.UserState) != sendGuid)
                {
                    return;
                }
                _client.SendCompleted -= handler;
                if (ea.Cancelled)
                {
                    tcs.SetCanceled();
                }
                else if (ea.Error != null)
                {
                    sendMailResponse.ErrorMessage = ea.Error.Message;
                    tcs.SetResult(sendMailResponse);
                }
                else
                {
                    sendMailResponse.IsSuccess = true;
                    tcs.SetResult(sendMailResponse);
                }
            };

            var msg = new MailMessage(request.From, request.Recipients.First())
            {
                From    = new MailAddress(request.From, request.FromName),
                Subject = request.Subject
            };

            var htmlMimeType = new ContentType("text/html");
            var textMimeType = new ContentType("text/plain");

            // Add text/plain as an AlternativeView
            var plainText     = HtmlText.ConvertHtml(request.Message);
            var plainTextView = AlternateView.CreateAlternateViewFromString(plainText);

            plainTextView.ContentType = textMimeType;
            msg.AlternateViews.Add(plainTextView);

            // Add text/html as an AlternateView
            var htmlView = AlternateView.CreateAlternateViewFromString(request.Message);

            htmlView.ContentType = htmlMimeType;
            msg.AlternateViews.Add(htmlView);

            foreach (var header in request.Headers)
            {
                msg.Headers.Add(header.Key, header.Value);
            }

            _client.SendCompleted += handler;
            _client.SendAsync(msg, sendGuid);

            return(tcs.Task);
        }