public async Task SendCoachNotificationEmail(IdentityMessage message, string from, string fromName, List <EmailAddress> tos, HttpPostedFileBase postFile)
        {
            var myMessage = new SendGridMessage();

            //myMessage.From = new EmailAddress(from, fromName);
            myMessage.From             = new EmailAddress("*****@*****.**", "Administrator");
            myMessage.Subject          = message.Subject;
            myMessage.PlainTextContent = message.Body;
            myMessage.HtmlContent      = $@"
            Hi
            <br/>
            {message.Body} <br/>
             <br/>
             <br/>
            Best Regards, <br/>
            Vibrant your body <br/>
            55 King Rd Autumn, VIC,9999 <br/>
            012345678<br/>
            <img src=http://cdn.mcauto-images-production.sendgrid.net/7d8250131a038040/684a1fec-03be-4dd8-b957-446d7e2cf5c6/569x320.jpg  width='200'>";

            myMessage.AddTos(tos);
            if (postFile != null)
            {
                await myMessage.AddAttachmentAsync(postFile.FileName, postFile.InputStream);
            }
            var apiKey   = ConfigurationManager.AppSettings["SendGridApi"];
            var client   = new SendGridClient(apiKey);
            var response = await client.SendEmailAsync(myMessage);

            Console.WriteLine(response.Body);
        }
Beispiel #2
0
 private void AddAttachments(MailConfig config, SendGridMessage mailMessage)
 {
     foreach (var attachment in config.Attachments)
     {
         mailMessage.AddAttachmentAsync(attachment.Key, attachment.Value);
     }
 }
        public async Task SendEmailAsyncWithAttachment(string email, string subject, string message, OrderDetailsVM order)
        {
            var client = new SendGridClient(_apiKey);
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress(_email, _from),
                Subject          = subject,
                PlainTextContent = message,
                HtmlContent      = message
            };

            msg.AddTo(new EmailAddress(email));

            msg.SetClickTracking(false, false);
            msg.SetOpenTracking(false);
            msg.SetGoogleAnalytics(false);
            msg.SetSubscriptionTracking(false);

            var path = @"A:\Programowanie\C#\Kurs\Apps\OnlineShop\OnlineShop.Web\Application\Services\PDFConverter\PDF\Invoice.pdf";

            _documentService.CreatePDF(order, null);

            using (var fileStream = File.OpenRead(path))
            {
                await msg.AddAttachmentAsync("Invoice.pdf", fileStream);

                var response = await client.SendEmailAsync(msg);
            }
            File.Delete(path);
        }
Beispiel #4
0
        public async Task SendEmailAsync(string subject, string htmlMessage, IFormFileCollection formFileCollection)
        {
            //var client = new SendGridClient(Environment.GetEnvironmentVariable("SENDGRID_API_KEY"));
            var client = new SendGridClient(_configuration["SENDGRID_API_KEY"]);

            var    fromEmail    = new EmailAddress(EmailConstants.Sender, EmailConstants.SenderName);
            var    toEmail      = new EmailAddress(EmailConstants.Receiver);
            string emailSubject = $"Bir müşteriniz {subject} formu doldurdu";
            string plainContent = htmlMessage;
            string htmlContent  = htmlMessage;

            SendGridMessage message = MailHelper.CreateSingleEmail(fromEmail, toEmail, emailSubject, plainContent, htmlContent);

            foreach (IFormFile file in formFileCollection)
            {
                // Create a unique filename in case someone uploads more than one document
                // with the same name (in which case the older attachment with the same
                // name gets removed).
                var    fileInfo    = new FileInfo(file.Name);
                string newFileName = $"{Guid.NewGuid()}{fileInfo.Extension}";

                await message.AddAttachmentAsync(newFileName, file.OpenReadStream(), file.ContentType);
            }

            try
            {
                var response = await client.SendEmailAsync(message);
            }
            catch (Exception)
            {
                // TODO: Log exception message to a log file.
                throw;
            }
        }
        public async Task SendEmailAsync(string email, string subject, string message)
        {
            var             apiKey    = Globals.SendGridApiKey;
            var             client    = new SendGridClient(apiKey);
            var             from      = new EmailAddress(Globals.SendGridEmail, Globals.EmailName);
            var             to        = new EmailAddress(email);
            var             htmlStart = "<!DOCTYPE html>";
            var             isHtml    = message.StartsWith(htmlStart);
            SendGridMessage msg       = MailHelper.CreateSingleEmail(from, to, subject, isHtml ? "See Html." : message, message);

            if (isHtml)
            {
                MemoryStream ms = new MemoryStream();
                StreamWriter sw = new StreamWriter(ms);
                await sw.WriteAsync(message);

                await sw.FlushAsync();

                ms.Seek(0, SeekOrigin.Begin);
                await msg.AddAttachmentAsync("FromNotes2021.html", ms);

                ms.Dispose();
            }

            Response response = await client.SendEmailAsync(msg);
        }
 internal async static Task AddAttachmentAsync(this SendGridMessage sendGridMessage, System.Net.Mail.Attachment attachment, CancellationToken cancellationToken = default)
 {
     var streamFileName = Path.GetFileName((attachment.ContentStream as FileStream)?.Name);
     await sendGridMessage.AddAttachmentAsync(
         filename : attachment.ContentDisposition.FileName ?? streamFileName,
         contentStream : attachment.ContentStream,
         type : attachment.ContentType.Name,
         disposition : attachment.ContentDisposition.Inline? "inline" : "attachment",
         content_id : attachment.ContentId,
         cancellationToken : cancellationToken
         );
 }
Beispiel #7
0
        public async Task SendGridMessage_AddAttachmentAsync_Doesnt_Read_Non_Readable_Streams()
        {
            // Arrange
            var sut = new SendGridMessage();

            var stream = new NonReadableStream();

            // Act
            await sut.AddAttachmentAsync(null, stream);

            // Assert
            Assert.Null(sut.Attachments);
        }
Beispiel #8
0
        public async Task SendGridMessage_AddAttachmentAsync_Doesnt_Add_If_Content_Stream_Is_Missing()
        {
            // Arrange
            var sut = new SendGridMessage();

            Stream contentStream = null;

            // Act
            await sut.AddAttachmentAsync("filename", contentStream);

            // Assert
            Assert.Null(sut.Attachments);
        }
Beispiel #9
0
        private async static Task <SendGridMessage> CreateMailAsync(
            Invoice invoice,
            Stream invoiceStream)
        {
            SendGridMessage message = new SendGridMessage();

            message.SetFrom(new EmailAddress("*****@*****.**", "Sender"));
            message.SetSubject($"Invoice {invoice.ID}");
            message.AddTo(new EmailAddress(invoice.MailTo, "Receiver"));

            message.AddContent("text/html", $"<strong>Invoice {invoice.ID}.</strong>");
            await message.AddAttachmentAsync($"{invoice.ID}.pdf", invoiceStream);

            return(message);
        }
Beispiel #10
0
        public async Task SendGridMessage_AddAttachmentAsync_Doesnt_Add_If_Filename_Is_Missing(string filename, string content)
        {
            // Arrange
            var sut = new SendGridMessage();

            var contentBytes         = Encoding.UTF8.GetBytes(content);
            var base64EncodedContent = Convert.ToBase64String(contentBytes);
            var contentStream        = new MemoryStream(contentBytes);

            // Act
            await sut.AddAttachmentAsync(filename, contentStream);

            // Assert
            Assert.Null(sut.Attachments);
        }
Beispiel #11
0
        public async Task <HttpStatusCode> SendBoardEmailMessageAsync(EmailDto emailDto, bool validFile, string fileType,
                                                                      CancellationToken cancellationToken)
        {
            var message = new SendGridMessage()
            {
                From        = new EmailAddress(emailDto.EmailFrom, SenderEmailName),
                Subject     = emailDto.Subject,
                HtmlContent = ConstructBoardEmailTemplate(emailDto.Message)
            };

            if (validFile)
            {
                //need to copy the IFormFile into a stream so that it can be attached to the email
                //unlike Azure Blob Storage, there is no method on the SendGrid client to attach a IFormFile directly
                using (var memoryStream = new MemoryStream())
                {
                    await emailDto.Attachment.CopyToAsync(memoryStream, cancellationToken);

                    //set the position to 0 so that the file is not empty
                    memoryStream.Position = 0;

                    //encode the file name
                    var fileName = WebUtility.HtmlEncode(Path.GetFileName(emailDto.Attachment.FileName));
                    //get the extension of the file for the server generated file name
                    var extension = fileName.Substring(fileName.IndexOf("."));

                    await message.AddAttachmentAsync($"Attachment-{DateTime.Now}{extension}", memoryStream, fileType, null, null, cancellationToken);
                }
            }

            var boardEmailList = await _iIDPUserService.GetBoardMemberEmails();

            //initialize a list of email addresses
            List <EmailAddress> messageEmails = new List <EmailAddress>();

            //convert each email fetched from the api and convert to an email address
            foreach (var item in boardEmailList)
            {
                messageEmails.Add(new EmailAddress(item));
            }

            //add the list of board emails to the message
            message.AddTos(messageEmails);

            var response = await client.SendEmailAsync(message, cancellationToken);

            return(response.StatusCode);
        }
Beispiel #12
0
        public void AttachEmailtoMessage(String storageConnectionString, String ContainerRefName, string fileName, SendGridMessage msg)
        {
            // Code for adding sender, recipient etc...
            var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
            var blobClient     = storageAccount.CreateCloudBlobClient();
            var container      = blobClient.GetContainerReference(ContainerRefName);
            var blob           = container.GetBlockBlobReference(fileName);
            var ms             = new MemoryStream();

            blob.DownloadToStreamAsync(ms).Wait();

            var blobBytes = GetBytesFromStream(ms);

            ms.Position = 0;
            msg.AddAttachmentAsync(fileName, ms).Wait();
        }
Beispiel #13
0
        public async Task ConfirmEvent([ActivityTrigger] ReportGeneration eventsData,
                                       [SendGrid(ApiKey = "SendGridConnections:ApiKey")] IAsyncCollector <SendGridMessage> messageCollector,
                                       ILogger log)
        {
            MemoryStream eventsStream = await fileService.DownloadReport(eventsData.ReportInformation.BlobContainerName, eventsData.ReportInformation.FileName);

            SendGridMessage message = new SendGridMessage();

            message.SetFrom(new EmailAddress(sendGridSettings.From));
            message.AddTos(adminSettings.GetMails().Select(x => new EmailAddress(x)).ToList());
            message.SetSubject($"Send events report from {eventsData.StartDate.ToShortDateString()} to {eventsData.EndDate.ToShortDateString()}");
            message.Contents = new List <Content>();
            message.Contents.Add(new Content("text/plain", "In this mail there is Event Report"));
            await message.AddAttachmentAsync(eventsData.FileName, eventsStream);

            await messageCollector.AddAsync(message);
        }
Beispiel #14
0
    public async Task <bool> SendAsync(NotifyMessage message)
    {
        var sendGridMessage = message as SendGridEmailMessage;

        if (sendGridMessage == null)
        {
            _logger.LogError("Invalid message type for SendGrid.");
            return(false);
        }

        if (string.IsNullOrEmpty(sendGridMessage.SendGridApiKey))
        {
            _logger.LogError($"No SendGrid Api Key provided. ==> {JsonUtil.Serialize(message)}");
            return(false);
        }

        var client = new SendGridClient(sendGridMessage.SendGridApiKey);
        var msg    = new SendGridMessage
        {
            From = new EmailAddress($"{message.Site.ToString().ToLowerInvariant()}@laobian.me",
                                    $"{message.Site} Notify"),
            Subject     = message.Subject,
            HtmlContent = GetHtmlContent(message)
        };

        foreach (var messageAttachment in message.Attachments)
        {
            await using (messageAttachment.Value)
            {
                await msg.AddAttachmentAsync(messageAttachment.Key, messageAttachment.Value);
            }
        }

        msg.AddTo(new EmailAddress(message.ToEmailAddress, message.ToName));
        var response = await client.SendEmailAsync(msg).ConfigureAwait(false);

        if (response.StatusCode != HttpStatusCode.Accepted)
        {
            _logger.LogError(await response.Body.ReadAsStringAsync());
            return(false);
        }

        _logger.LogInformation($"Email notify sent, subject = {message.Subject}.");
        return(true);
    }
Beispiel #15
0
        public async Task SendGridMessage_AddAttachmentAsync_Adds_Base64_Content_Of_Stream()
        {
            // Arrange
            var sut = new SendGridMessage();

            var content              = "hello world";
            var contentBytes         = Encoding.UTF8.GetBytes(content);
            var base64EncodedContent = Convert.ToBase64String(contentBytes);
            var stream = new MemoryStream(contentBytes);

            // Act
            await sut.AddAttachmentAsync("filename", stream);

            // Assert
            Assert.Single(sut.Attachments);

            var attachment = sut.Attachments.First();

            Assert.Equal(attachment.Content, base64EncodedContent);
        }
        public static async Task Run(
            [BlobTrigger("current/{name}")]
            Stream inputBlob,
            string name,
            [SendGrid(ApiKey = "")]
            IAsyncCollector <SendGridMessage> messageCollector,
            TraceWriter log)
        {
            log.Info($"C# Blob trigger function Processed blob Name:{name} Size: {inputBlob.Length} Bytes");

            SendGridMessage message = new SendGridMessage();

            message.AddTo(new EmailAddress(ConfigurationManager.AppSettings["EmailAddressTo"]));
            message.From = new EmailAddress(ConfigurationManager.AppSettings["EmailAddressFrom"]);
            message.SetSubject("RPI Web camera Image attached");
            message.AddContent("text/plain", $"{name} {inputBlob.Length} bytes");

            await message.AddAttachmentAsync(name, inputBlob, "image/jpeg");

            await messageCollector.AddAsync(message);
        }
        public static async Task <dynamic> SendGridEmail(string htmlString, string email, string subject, MemoryStream ms = null)
        {
            var client = new SendGridClient(sendgridApiKey);
            var msgs   = new SendGridMessage()
            {
                From        = new EmailAddress("*****@*****.**"),
                Subject     = subject,
                HtmlContent = htmlString
            };

            msgs.AddTo(new EmailAddress(email));
            if (ms != null)
            {
                ms.Position = 0;
                await msgs.AddAttachmentAsync("Test.pdf", ms, "application/pdf");
            }
            /*msgs.SetFooterSetting(true, "<strong>Regards,</strong><b> Pankaj Sapkal", "Pankaj");*/
            //Tracking (Appends an invisible image to HTML emails to track emails that have been opened)
            //msgs.SetClickTracking(true, true);
            var response = await client.SendEmailAsync(msgs);

            return(response);
        }
Beispiel #18
0
        public async Task SendGridMessage_AddAttachmentAsync_Should_Add_Single_Attachment_To_Attachments(string filename, string content, string type, string disposition, string contentId)
        {
            // Arrange
            var sut = new SendGridMessage();

            var contentBytes         = Encoding.UTF8.GetBytes(content);
            var base64EncodedContent = Convert.ToBase64String(contentBytes);
            var contentStream        = new MemoryStream(contentBytes);

            // Act
            await sut.AddAttachmentAsync(filename, contentStream, type, disposition, contentId);

            // Assert
            Assert.Single(sut.Attachments);

            var addedAttachment = sut.Attachments.First();

            Assert.Equal(base64EncodedContent, addedAttachment.Content);
            Assert.Equal(contentId, addedAttachment.ContentId);
            Assert.Equal(disposition, addedAttachment.Disposition);
            Assert.Equal(filename, addedAttachment.Filename);
            Assert.Equal(type, addedAttachment.Type);
        }
 internal static async Task AddAttachmentsAsync(this SendGridMessage sendGridMessage, IEnumerable <System.Net.Mail.Attachment> attachments, CancellationToken cancellationToken = default)
 {
     await Task.WhenAll(
         attachments.Select(a => sendGridMessage.AddAttachmentAsync(a, cancellationToken))
         );
 }