示例#1
0
        public async Task <bool> SendEmailWithInformation(string email, string flightContent = null, string hotelContent = null)
        {
            var apiKey = _configuration.SendGridApiKey;
            var client = new SendGridClient(apiKey);

            var msg = new SendGridMessage()
            {
                From        = new EmailAddress("*****@*****.**", "Booking information from your request"),
                Subject     = "Information about your booking request",
                HtmlContent = "Sending you information in data readable format :)"
            };

            msg.AddTo(email);

            if (flightContent != null)
            {
                msg.AddAttachment(CreateAttachmentFromContent(flightContent, "flight.json"));
            }

            if (hotelContent != null)
            {
                msg.AddAttachment(CreateAttachmentFromContent(hotelContent, "hotel.json"));
            }

            var response = await client.SendEmailAsync(msg);

            var responseBody = await response.Body.ReadAsStringAsync();

            return(response.StatusCode == HttpStatusCode.Accepted);
        }
        public Task SendEmailWithAttachmentsAsync(List <string> to, string bcc, string cc, string subject, string body, List <AttachmentModel> attachments)
        {
            SendGridMessage myMessage = new SendGridMessage();

            myMessage.AddTo(to);
            if (!string.IsNullOrEmpty(bcc))
            {
                myMessage.AddCc(bcc);
            }
            if (!string.IsNullOrEmpty(cc))
            {
                myMessage.AddCc(cc);
            }

            myMessage.From    = new MailAddress(FromEmail, FromName);
            myMessage.Subject = (Environment != null? $"{Environment}_{subject}":subject);
            myMessage.Html    = body;
            foreach (var attachment in attachments)
            {
                if (string.IsNullOrEmpty(Environment))
                {
                    myMessage.AddAttachment(attachment.Stream, attachment.Name);
                }
                else
                {
                    myMessage.AddAttachment(attachment.Stream, $"{Environment}_{attachment.Name}");
                }
            }
            // Create a Web transport, using API Key
            var transportWeb = new Web(ApiKey);

            // Send the email.
            return(transportWeb.DeliverAsync(myMessage));
        }
示例#3
0
        public void AddAttachments(BlobDownloadInfo medicalDownload, BlobDownloadInfo downloadInstructions)
        {
            BinaryReader medicalReader = new BinaryReader(medicalDownload.Content);

            Byte[] medicalBytes = medicalReader.ReadBytes(Convert.ToInt32(medicalDownload.ContentLength));
            _message.AddAttachment("Athlete_Registration,_Release_and_Medical_Form4.pdf", Convert.ToBase64String(medicalBytes, 0, medicalBytes.Length));
            BinaryReader instructionReader = new BinaryReader(downloadInstructions.Content);

            Byte[] instructionBytes = instructionReader.ReadBytes(Convert.ToInt32(downloadInstructions.ContentLength));
            _message.AddAttachment("Instructions for Area 23 Medical Forms.docx", Convert.ToBase64String(instructionBytes, 0, instructionBytes.Length));
        }
示例#4
0
        public Task SendResetPasswordEmail(string recipient, string callbackUrl)
        {
            var client = new SendGridClient(Options.SendGridApiKey);

            string htmlMessage =
                @"<div align=""center""><img height=""120"" src=""cid:KutlanCoder"" /></div>
                <br />
                <div style=""font-family: &quot;Segoe UI&quot;; text-align: center"">You can reset your password by clicking the link below.</div>
                <div style=""font-family: &quot;Segoe UI&quot;; text-align: center"">If you didn't request a password reset, please discard this email.</div>
                <br />
                <div align=""center"" bgcolor=""#1338d3"" style=""border-radius:6px; font-size:16px; text-align:center; background-color:inherit;"">
                  <a href={0}><img height=""40"" src=""cid:ResetButton"" /></a>
                </div>";
            var msg = new SendGridMessage()
            {
                From             = new EmailAddress(Options.SendGridFromEmail, Options.SendGridFromName),
                Subject          = "Reset Your Password",
                PlainTextContent = $"You can reset your password by clicking the following link. {HtmlEncoder.Default.Encode(callbackUrl)} If you didn't request a password reset, please discard this email.",
                HtmlContent      = String.Format(htmlMessage, HtmlEncoder.Default.Encode(callbackUrl))
            };

            msg.AddTo(new EmailAddress(recipient));

            //Add KutlanCoder logo inline attachment with a content id, in order to embed the image into the email.
            Byte[] bytes  = File.ReadAllBytes(Path.Combine(_webHostEnvironment.WebRootPath, "Images\\KutlanCoder.png"));
            String base64 = Convert.ToBase64String(bytes);

            msg.AddAttachment(new Attachment()
            {
                Content     = base64,
                Type        = "image/png",
                Filename    = "KutlanCoder.png",
                Disposition = "inline",
                ContentId   = "KutlanCoder" //Must match the cid in the html.
            });

            //Add "Confirm Your Email" button inline attachment with a content id, in order to embed the image into the email.
            bytes  = File.ReadAllBytes(Path.Combine(_webHostEnvironment.WebRootPath, "Images\\ResetYourPasswordButton.png"));
            base64 = Convert.ToBase64String(bytes);
            msg.AddAttachment(new Attachment()
            {
                Content     = base64,
                Type        = "image/png",
                Filename    = "ResetYourPasswordButton.png",
                Disposition = "inline",
                ContentId   = "ResetButton" //Must match the cid in the html.
            });

            // Disable click tracking.
            msg.SetClickTracking(false, false);

            return(client.SendEmailAsync(msg));
        }
示例#5
0
        public async Task SendEmailWithAttachmentsAsync(List <string> to, string subject,
                                                        string body, List <EmailAttachment> attachments, string bcc = null, string cc = null)
        {
            SendGridMessage myMessage = new SendGridMessage();

            foreach (var toMail in to)
            {
                myMessage.AddTo(new EmailAddress(toMail));
            }
            if (!string.IsNullOrEmpty(bcc))
            {
                myMessage.AddCc(new EmailAddress(bcc));
            }
            if (!string.IsNullOrEmpty(cc))
            {
                myMessage.AddCc(new EmailAddress(cc));
            }

            myMessage.From        = new EmailAddress(_sendGridConfigure.FromEmail, _sendGridConfigure.FromName);
            myMessage.Subject     = subject;
            myMessage.HtmlContent = body;
            foreach (var attachment in attachments)
            {
                var bytes = await ReadFully(attachment.Attachment);

                myMessage.AddAttachment(attachment.FileName, Convert.ToBase64String(bytes));
            }
            var client = new SendGridClient(_sendGridConfigure.ApiKey);
            // Create a Web transport, using API Key
            await client.SendEmailAsync(myMessage);
        }
示例#6
0
        public void SendGridMessage_AddAttachment_Doesnt_Touch_Attachment_Passed_In()
        {
            // Arrange
            var sut = new SendGridMessage();

            var content     = "content";
            var contentId   = "contentId";
            var disposition = "disposition";
            var filename    = "filename";
            var type        = "type";

            var attachment = new Attachment
            {
                Content     = content,
                ContentId   = contentId,
                Disposition = disposition,
                Filename    = filename,
                Type        = type
            };

            // Act
            sut.AddAttachment(attachment);

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

            var addedAttachment = sut.Attachments.First();

            Assert.Same(attachment, addedAttachment);
            Assert.Equal(attachment.Content, addedAttachment.Content);
            Assert.Equal(attachment.ContentId, addedAttachment.ContentId);
            Assert.Equal(attachment.Disposition, addedAttachment.Disposition);
            Assert.Equal(attachment.Filename, addedAttachment.Filename);
            Assert.Equal(attachment.Type, addedAttachment.Type);
        }
示例#7
0
        private static async Task SendEmail(string email, string subject, JObject data)
        {
            var client = new SendGridClient(
                ConfigurationManager.AppSettings["SendGridApiKey"]);

            var msg = new SendGridMessage();

            msg.SetFrom(new EmailAddress(
                            ConfigurationManager.AppSettings["EmailFrom"]));

            var recipients = new List <EmailAddress> {
                new EmailAddress(email)
            };

            msg.AddTos(recipients);

            msg.SetSubject(subject);

            msg.AddAttachment("Event.json",
                              ToBase64(data.ToString(Formatting.Indented)), "application/json");

            msg.AddContent(MimeType.Text, data.ToString(Formatting.None));

            var response = await client.SendEmailAsync(msg);
        }
        public async Task SendEmailAsync(string userEmail, string emailSubject, string message, int?bestellingsId = null, MemoryStream stream = null)
        {
            //var apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
            var apiKey = "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";
            var client = new SendGridClient(apiKey);
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "dotNetAcadamy"),
                Subject          = emailSubject,
                PlainTextContent = message,
                HtmlContent      = message
            };

            msg.AddTo(new EmailAddress(userEmail, ""));
            msg.SetFooterSetting(true,
                                 "<p style='color: grey;'>Dit is een automatische mail van dotNetAcademy™</p>",
                                 "Dit is een automatische mail van dotNetAcademy™");

            if (bestellingsId != null && stream != null)
            {
                msg.AddAttachment(CreateAttachment(bestellingsId.Value, stream));
            }

            var response = await client.SendEmailAsync(msg);
        }
        public void EmailReceipt(byte[] file, string fileName, OrderViewModel order)
        {
            // Set our SendGrid API User and Key values for authenticating our transport.
            var sendGridApiKey  = "";
            var sendGridApiUser = "";

            // Create the email object first, and then add the properties.
            var myMessage = new SendGridMessage();

            // Add the message properties.
            myMessage.From = new MailAddress("*****@*****.**");

            // Add customer's email addresses to the To field.
            myMessage.AddTo(order.Email);

            myMessage.Subject = "Contoso Sports League order received";

            // Add the HTML and Text bodies.
            myMessage.Html = "";
            myMessage.Text = "";

            // Add our generated PDF receipt as an attachment.
            using (var stream = new MemoryStream(file))
            {
                myMessage.AddAttachment(stream, fileName);
            }

            var credentials = new NetworkCredential(sendGridApiUser, sendGridApiKey);
            // Create a Web transport using our SendGrid API user and key.
            var transportWeb = new Web(credentials);

            // Send the email.
            transportWeb.DeliverAsync(myMessage);
        }
示例#10
0
        public static async Task SendEmail(string[] recipients, string subject, string body, bool isHtml, Dictionary <string, MemoryStream> attachments)
        {
            string apiKey = Settings.SendGrid.ApiKey;
            var    client = new SendGridClient(apiKey);

            var msg = new SendGridMessage();

            msg.From    = new EmailAddress("noreply@" + Settings.Domain);
            msg.Subject = subject;
            if (isHtml)
            {
                msg.HtmlContent = body;
            }
            else
            {
                msg.PlainTextContent = body;
            }
            foreach (string recipient in recipients)
            {
                msg.AddTo(new EmailAddress(recipient));
            }

            if (attachments != null)
            {
                foreach (KeyValuePair <string, MemoryStream> kvp in attachments)
                {
                    msg.AddAttachment(kvp.Key, Convert.ToBase64String(kvp.Value.ToArray()), disposition: "attachment");
                }
            }

            await client.SendEmailAsync(msg);
        }
        public static SendGridMessage ToSendGridMessage(this MailMessageDto dto)
        {
            if (dto.Sender != null)
            {
                throw new NotSupportedException("Sender header is not supported by SendGrid.");
            }
            if ((dto.ReplyTo?.Count ?? 0) > 1)
            {
                throw new NotSupportedException("Only one Reply-To header is supported by SendGrid.");
            }

            var msg = new SendGridMessage();

            // Add standard header fields
            msg.From = dto.From.ToEmailAddress();
            if (dto.To.Any())
            {
                msg.AddTos(dto.To.ToEmailAddress());
            }
            if (dto.Cc.Any())
            {
                msg.AddCcs(dto.Cc.ToEmailAddress());
            }
            if (dto.Bcc.Any())
            {
                msg.AddBccs(dto.Bcc.ToEmailAddress());
            }
            msg.ReplyTo = dto.ReplyTo.FirstOrDefault().ToEmailAddress();
            msg.Subject = dto.Subject;

            // Add custom header fields
            foreach (var item in dto.CustomHeaders)
            {
                msg.Headers.Add(item.Key, item.Value);
            }

            // Construct body
            if (!string.IsNullOrWhiteSpace(dto.BodyText))
            {
                msg.PlainTextContent = dto.BodyText;
            }
            if (!string.IsNullOrWhiteSpace(dto.BodyHtml))
            {
                msg.HtmlContent = dto.BodyHtml;
            }

            // Add attachments
            foreach (var item in dto.Attachments)
            {
                // Get stream as byte array
                var data = new byte[item.Stream.Length];
                item.Stream.Read(data, 0, (int)item.Stream.Length);

                // Base64 encode
                var encodedData = Convert.ToBase64String(data, 0, data.Length);
                msg.AddAttachment(item.Name, encodedData, item.MimeType);
            }

            return(msg);
        }
示例#12
0
        [return : SendGrid(To = "*****@*****.**", From = "*****@*****.**")] //TODO config
        public async Task <SendGridMessage> SendClientEmail([ActivityTrigger] Client client, ILogger log)
        {
            var message = new SendGridMessage();

            message.AddContent("text/html", EmailContent(client));
            message.Subject = $"{client.Name} - Onboarding Confirmation";

            var response = await httpClient.GetAsync(client.DocumentUrl);

            var bytes = await response.Content.ReadAsByteArrayAsync();

            message.AddAttachment(new Attachment()
            {
                Content     = Convert.ToBase64String(bytes),
                Filename    = $"{client.Name}-Document.txt",
                Type        = "text/plain",
                Disposition = "attachment"
            });

            client.EmailSent = DateTime.Now;
            dbContext.Clients.Update(client);
            await dbContext.SaveChangesAsync();

            return(message);
        }
示例#13
0
        public async Task <Tuple <string, string, string> > Execute(string filePath)
        {
            try
            {
                var apiKey       = EmailComponents.apiKey;
                var client       = new SendGridClient(apiKey);
                var messageEmail = new SendGridMessage()
                {
                    From             = new EmailAddress(EmailComponents.fromEmail, EmailComponents.fromEmaliUserName),
                    Subject          = EmailComponents.Subject,
                    PlainTextContent = EmailComponents.plainTextContent,
                    HtmlContent      = EmailComponents.htmlContent
                };
                messageEmail.AddTo(new EmailAddress(EmailComponents.emailTo, EmailComponents.emailToUserName));
                var bytes = File.ReadAllBytes(filePath);
                var file  = Convert.ToBase64String(bytes);
                messageEmail.AddAttachment("Voucher Details Report.pdf", file);


                var response = await client.SendEmailAsync(messageEmail);

                return(new Tuple <string, string, string>(response.StatusCode.ToString(),
                                                          response.Headers.ToString(),
                                                          response.Body.ToString()));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <VQSendEmailResult> SendEmail(VQEmail email)
        {
            ValidateEmail(email);

            var client = new SendGridClient(SendGridToken);
            var msg    = new SendGridMessage
            {
                From        = new EmailAddress(email.From.Email, email.From.Name.IsNullOrWhiteSpaceOr(email.From.Email)),
                Subject     = email.Subject,
                HtmlContent = email.Body
            };

            if (email.To.ListHasItem())
            {
                email.To.ForEach(x => msg.AddTo(new EmailAddress(x.Email, x.Name.IsNullOrWhiteSpaceOr(x.Email))));
            }

            if (email.Attachments.ListHasItem())
            {
                email.Attachments.ForEach(x => msg.AddAttachment(new Attachment
                {
                    Content  = Convert.ToBase64String(x.Content),
                    Type     = x.Type,
                    Filename = x.Name
                }));
            }

            var response = await client.SendEmailAsync(msg);

            return(await ConvertResponseEmail(response));
        }
示例#15
0
        private void AddAttachment(SendGridMessage mail, string filename, string content)
        {
            var bytes         = Encoding.ASCII.GetBytes(content);
            var base64Content = Convert.ToBase64String(bytes);

            mail.AddAttachment(filename, base64Content);
        }
示例#16
0
        public Task Execute(string apiKey, string subject, string message, string email)
        {
            var client = new SendGridClient(apiKey);

            var msg = new SendGridMessage()
            {
                From             = new EmailAddress("*****@*****.**", "Michael Adaikalaraj"),
                Subject          = subject,
                PlainTextContent = message,
                HtmlContent      = message
            };

            msg.AddTo(new EmailAddress(email));
            if (subject.Equals("Demo"))
            {
                var bytes = File.ReadAllBytes("wwwroot/images/ai.png");
                var file  = Convert.ToBase64String(bytes);
                msg.AddAttachment("file.png", file);
            }

            // Disable click tracking.
            // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html
            msg.SetClickTracking(false, false);

            return(client.SendEmailAsync(msg));
        }
示例#17
0
        private void SendZipFileToRecipients(Options options, byte[] policies)
        {
            using (MemoryStream ms = new MemoryStream(policies))
            {
                SendGridMessage message = new SendGridMessage();

                string subject = $"{options.EmailSubject} {DateUtil.CurrentDateTime}";

                message.To      = options.ToEmailAddressesAsList().Select(email => new MailAddress(email)).ToArray();
                message.Subject = subject;
                message.From    = new MailAddress(options.FromEmailAddress, "RAC Bicycle Insurance");
                message.ReplyTo = new MailAddress[] { message.From };
                message.AddAttachment(ms, "DataExtract.zip");
                message.Text = "Attached is the Bike Insurance data extract for " + DateUtil.CurrentDateTime.ToLongTimeString();

                Web transportWeb = new Web(options.SendGridApiKey);

                Task task = Task.Run(async() =>
                {
                    try
                    {
                        await transportWeb.DeliverAsync(message);
                    }
                    catch (InvalidApiRequestException e)
                    {
                        foreach (string error in e.Errors)
                        {
                            Console.WriteLine("Error: " + error);
                        }
                    }
                });

                task.Wait(TimeSpan.FromSeconds(30));
            }
        }
示例#18
0
        public static void SendEmail(string[] recipients, string subject, string body, Tuple <string, byte[]>[] attachments = null)
        {
            if (recipients == null || recipients.Length == 0 || recipients.All(x => string.IsNullOrWhiteSpace(x)))
            {
                throw new Exception("Unable to send email using SendGrid as no recipients have been provided");
            }

            var client = new SendGridClient(WebRequest.DefaultWebProxy, _apikey);
            var msg    = new SendGridMessage()
            {
                From             = new EmailAddress(_fromaddress),
                Subject          = subject,
                PlainTextContent = body
            };

            foreach (var recipient in recipients)
            {
                if (!string.IsNullOrWhiteSpace(recipient))
                {
                    msg.AddTo(new EmailAddress(recipient));
                }
            }

            if (attachments != null)
            {
                foreach (var attachment in attachments)
                {
                    msg.AddAttachment(attachment.Item1, Convert.ToBase64String(attachment.Item2));
                }
            }

            client.SendEmailAsync(msg);
        }
示例#19
0
        //public EmailHelper(string toEmailAddress, string subject, string message, string attachmentPath)
        //    : this(toEmailAddress, subject, message)
        //{
        //    this.attachmentPath = attachmentPath;
        //}

        #endregion

        #region Functions

        public void SendMessage()
        {
            SendGridMessage myMessage = new SendGridMessage();

            myMessage.AddTo(toEmailAddress);
            myMessage.From = new MailAddress(fromEmailAddress, (string.IsNullOrEmpty(fromUserName) ? fromEmailAddress : fromUserName));

            if (!string.IsNullOrEmpty(bccEmailAddress))
            {
                myMessage.AddBcc(bccEmailAddress);
            }

            myMessage.Subject = subject;
            myMessage.Html    = message;

            if (!string.IsNullOrEmpty(attachmentPath))
            {
                myMessage.AddAttachment(attachmentPath);
            }

            var credentials = new NetworkCredential(sendGridUserName, sendGridPassword);

            // Create an Web transport for sending email.
            var transportWeb = new Web(credentials);

            // Send the email, which returns an awaitable task.
            var oRet = transportWeb.DeliverAsync(myMessage);
        }
        public static async Task Run(
            [BlobTrigger("licenses/{orderId}.lic", Connection = "AzureWebJobsStorage")] string licenseFileContents,
            [SendGrid(ApiKey = "SendGridApiKey")] ICollector <SendGridMessage> mailSender,
            IBinder binder,
            string orderId,
            ILogger log)
        {
            var order = await binder.BindAsync <Order>(
                new TableAttribute("orders", "orders", orderId)
            {
                Connection = "AzureWebJobsStorage"
            });

            var message = new SendGridMessage();

            message.From = new EmailAddress(Environment.GetEnvironmentVariable("EmailSender"));
            message.AddTo(order.Email);

            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(licenseFileContents);
            var base64         = Convert.ToBase64String(plainTextBytes);

            message.AddAttachment(filename: orderId + ".lic", content: base64, type: "text/plain");
            message.Subject     = "Your license file";
            message.HtmlContent = "Thank you for your order";

            mailSender.Add(message);

            log.LogInformation("Email Sent Successfully!");
        }
        public static void Run([BlobTrigger("licenses/{orderId}.lic",
                                            Connection = "AzureWebJobsStorage")] string licenseFileContents,
                               [SendGrid(ApiKey = "SendGridApiKey")] ICollector <SendGridMessage> sender,
                               [Table("orders", "orders", "{orderId}")] Order order,
                               string orderId,
                               ILogger log)
        {
            var email = order.Email;

            log.LogInformation($"Got order from {email}\n Order Id:{orderId}");
            var message = new SendGridMessage
            {
                From = new EmailAddress(Environment.GetEnvironmentVariable("EmailSender"))
            };

            message.AddTo(email);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(licenseFileContents);
            var base64         = Convert.ToBase64String(plainTextBytes);

            message.AddAttachment($"{orderId}.lic", base64, "text/plain");
            message.Subject     = "Your license file";
            message.HtmlContent = "Thank you for your order";
            if (!email.EndsWith("@test.com"))
            {
                sender.Add(message);
            }
        }
示例#22
0
        public async Task Send(String toEmail, String subject, String contents, string upload, string fileName)
        {
            var apiKey           = Environment.GetEnvironmentVariable(API_KEY);
            var client           = new SendGridClient(API_KEY);
            var from             = new EmailAddress("*****@*****.**", "FIT5032 Example Email User");
            var to               = new EmailAddress(toEmail, "");
            var to1              = new EmailAddress(toEmail, "");
            var plainTextContent = contents;
            var htmlContent      = "<p>" + contents + "</p>";
            var msg              = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
            var message          = new SendGridMessage();

            message.From = from;

            message.AddTo(to);
            message.AddTo(to1);
            message.Subject          = subject;
            message.HtmlContent      = htmlContent;
            message.PlainTextContent = plainTextContent;
            if (upload != null)
            {
                var bytes = File.ReadAllBytes(upload);
                var file  = Convert.ToBase64String(bytes);
                message.AddAttachment(fileName, file);
            }
            var response = await client.SendEmailAsync(message);
        }
示例#23
0
        private static SendGridMessage CreateMessage(EmailRequest request)
        {
            const string emptyHtml = "<span></span>";
            const string emptyText = "";
            var          subject   = request.Subject ?? " ";

            //to support multiple email ids in to field
            MailAddress[] toEmailAddresses = ParseEmailList(request.ToEmail);

            // NOTE: https://github.com/sendgrid/sendgrid-csharp.
            var message = new SendGridMessage
            {
                Subject = subject,
                To      = toEmailAddresses,
                Text    = emptyText,
                Html    = emptyHtml,
            };

            //Append the attachment if any
            if (!string.IsNullOrEmpty(request.StreamedAttachmentName))
            {
                message.AddAttachment(request.StreamedAttachmentName);
            }

            return(message);
        }
示例#24
0
        private void SendReportsToRecipients(string sendGridKey, string reportsToRecipients, string crmInstanceName, List <string> generatedFiles, string reportName)
        {
            var client = new SendGridClient(sendGridKey);
            var msg    = new SendGridMessage()
            {
                From        = new EmailAddress("*****@*****.**"),
                Subject     = $"{crmInstanceName} Audit Report",
                HtmlContent = $"<p>{crmInstanceName} Audit Report</p>"
            };

            foreach (var generatedFile in generatedFiles)
            {
                var bytes         = File.ReadAllBytes(generatedFile);
                var content       = Convert.ToBase64String(bytes);
                var filename      = generatedFile.Split(new[] { "\\" }, StringSplitOptions.RemoveEmptyEntries).Last();
                var fileExtension = filename.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries).Last();
                msg.AddAttachment($"{reportName}.{fileExtension}", content);
            }

            var emails = reportsToRecipients.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();

            foreach (var email in emails)
            {
                msg.AddTo(new EmailAddress(email));
            }

            var response = client.SendEmailAsync(msg).Result;
        }
        public void send(String toEmail, String messageSubject,
                         String messageBody, String fullPath, String fileName)
        {
            string[] emailAddresses = toEmail.Split(',');
            var      client         = new SendGridClient(API_KEY);
            var      to_emails      = new List <EmailAddress>();

            for (int i = 0; i < emailAddresses.Length; i++)
            {
                to_emails.Add(new EmailAddress(emailAddresses[i], "User"));
            }
            ;
            var msg = new SendGridMessage();

            msg.SetFrom("*****@*****.**", "FIT5032 BULK EMAIL");
            var plainTextContent = messageBody;
            var htmlContent      = "<p>" + messageBody + "</p>";

            msg.PlainTextContent = plainTextContent;
            msg.Subject          = messageSubject;
            msg.AddTos(to_emails);

            if (fullPath == "nothing")
            {
                //msg.AddAttachment(model.AttachedFile.FileName, file);
                var response = client.SendEmailAsync(msg);
            }
            else
            {
                var bytes = System.IO.File.ReadAllBytes(fullPath);
                var file  = Convert.ToBase64String(bytes);
                msg.AddAttachment(fileName, file);
                var response = client.SendEmailAsync(msg);
            }
        }
示例#26
0
        public static async Task EmailLicenseFileActivity(
            [ActivityTrigger] Order order,
            [SendGrid(ApiKey = "SendGridApiKey")] ICollector <SendGridMessage> sender,
            IBinder binder,
            ILogger log)
        {
            var licenseFileContents = await binder.BindAsync <string>(
                new BlobAttribute($"licenses/{order.Id}.lic"));

            var email = order.Email;

            log.LogInformation($"Got order from {email}\n Order Id:{order.Id}");
            var message = new SendGridMessage();

            message.From = new EmailAddress(Environment.GetEnvironmentVariable("EmailSender"));
            message.AddTo(email);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(licenseFileContents);
            var base64         = Convert.ToBase64String(plainTextBytes);

            message.AddAttachment($"{order.Id}.lic", base64, "text/plain");
            message.Subject     = "Your license file";
            message.HtmlContent = "Thank you for your order";
            if (!email.EndsWith("@test.com"))
            {
                sender.Add(message);
            }
        }
示例#27
0
        // email is sending Async using Thread > so UI will not show progrssbar for long time untill method is not completed
        internal static bool sendMail(string EmailId, string subject, string body, string fromEmail, string attachment = null)
        {
            string user    = ConfigurationManager.AppSettings["userName"];
            string pasword = ConfigurationManager.AppSettings["Password"];

            try
            {
                SendGridMessage myMessage = new SendGridMessage();
                myMessage.AddTo(EmailId);
                myMessage.From    = new MailAddress(fromEmail);
                myMessage.Subject = subject;
                myMessage.Html    = body;

                if (attachment != null)
                {
                    myMessage.AddAttachment(attachment);
                }

                // Create credentials, specifying your user name and password.
                var credentials = new NetworkCredential(user, pasword);

                // Create an Web transport for sending email.
                var transportWeb = new Web(credentials);

                // Send the email, which returns an awaitable task.
                transportWeb.DeliverAsync(myMessage);

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        public static void Run(
            //[BlobTrigger("licenses/{name}", Connection = "AzureWebJobsStorage")]string licenseFileContents,
            //[SendGrid(ApiKey = "SendGridApiKey")] out SendGridMessage message,
            [BlobTrigger("licenses/{orderId}.lic", Connection = "AzureWebJobsStorage")] string licenseFileContents,
            [SendGrid(ApiKey = "SendGridApiKey")] ICollector <SendGridMessage> mailSender,
            [Table("orders", "orders", "{orderId}")] OrderStorage orderStorage, //fetches data from table storage
            string orderId,
            ILogger log)
        {
            log.LogInformation($"Got license file for: {orderStorage.Email}\n License filename: {orderId}");

            var message = new SendGridMessage();

            message.From = new EmailAddress(Environment.GetEnvironmentVariable("EmailSender"));
            message.AddTo(orderStorage.Email);
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(licenseFileContents);
            var base64         = Convert.ToBase64String(plainTextBytes);

            message.AddAttachment(orderId, base64, "text/plain");
            message.Subject     = "Your License File";
            message.HtmlContent = "Thank you for you order";

            if (!orderStorage.Email.EndsWith("@test.com"))
            {
                mailSender.Add(message);
            }
        }
示例#29
0
        public async Task <bool> SendEmailAsync(string emailto, string subject, object message, string templateid = null, string attachmentsfile = null)
        {
            var client = new SendGridClient(_configuration["Sendgrid:Apikey"]);
            var msg    = new SendGridMessage();

            msg.SetFrom(new SendGrid.Helpers.Mail.EmailAddress(_configuration["Sendgrid:Emailfrom"]));
            msg.AddTo(new SendGrid.Helpers.Mail.EmailAddress(emailto));
            //body = "Email Body";
            msg.Subject = subject;
            if (templateid != null)
            {
                msg.SetTemplateId(templateid);
                var h = JsonConvert.SerializeObject(new { templatedata = message });
                msg.SetTemplateData(new { templatedata = message });
            }
            if (attachmentsfile != null)
            {
                msg.AddAttachment("orderreceipt.pdf", attachmentsfile, "application/pdf");

                /**
                 * msg.AddAttachment(
                 *  new Attachment
                 *  {
                 *      Filename = "orderreceipt",
                 *      Content = attachments,
                 *      Type = MimeType.Text.,
                 *      Disposition = "attachment",
                 *      ContentId = Guid.NewGuid().ToString()
                 *  }
                 *  );**/
            }
            var response = await client.SendEmailAsync(msg);

            return(response.StatusCode == HttpStatusCode.Accepted ? true : false);
        }
        public SentStatus Send(string to, string subject, string message, string[] cc, string[] bcc, byte[] attachment, string attachmentname, string replyto)
        {
            bool   status;
            string responseMesage = string.Empty;

            try
            {
                SendGridMessage msg = new SendGridMessage
                {
                    From             = new EmailAddress(Config.EmailAddress, Config.Name),
                    Subject          = subject,
                    PlainTextContent = message,
                    ReplyTo          = new EmailAddress(replyto)
                };
                msg.AddTo(new EmailAddress(to, "User"));
                foreach (string i in cc)
                {
                    msg.AddBcc(new EmailAddress(i));
                }
                foreach (string i in bcc)
                {
                    msg.AddCc(new EmailAddress(i));
                }
                if (attachment != null)
                {
                    var file = Convert.ToBase64String(attachment);
                    msg.AddAttachment(attachmentname, file);
                }
                Client.SendEmailAsync(msg);
                responseMesage = "SendGrid Send success";
                status         = true;
            }
            catch (Exception e)
            {
                responseMesage = "SendGrid Send Exception" + e.Message + e.StackTrace;
                status         = false;
            }
            var        plainTextBytes = Encoding.UTF8.GetBytes(message);
            string     message64      = Convert.ToBase64String(plainTextBytes);
            SentStatus SentStatus     = new SentStatus
            {
                Status     = status.ToString(),
                To         = to,
                From       = Config.EmailAddress,
                Body       = message64,
                ConId      = Config.Id,
                Result     = responseMesage,
                Recepients = new EmailRecepients
                {
                    To      = to,
                    Cc      = (cc == null) ? "" : string.Join(",", cc),
                    Bcc     = (bcc == null) ? "" : string.Join(",", bcc),
                    Replyto = (replyto == null) ? "" : replyto,
                },
                Subject        = subject,
                AttachmentName = attachmentname
            };

            return(SentStatus);
        }
        public void Attachment()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Subject = "file attachment";
            message.Text = "file attachment test";

            message.AddAttachment(ConfigurationManager.AppSettings["AttachmentImage"]);

            client.Send(message);
        }
        public void EmbedImage()
        {
            var client = new SendGridClient(ConfigurationManager.AppSettings["ApiKey"]);

            var message = new SendGridMessage();

            message.To.Add(ConfigurationManager.AppSettings["MailTo"]);
            message.From = ConfigurationManager.AppSettings["MailFrom"];

            message.Subject = "file attachment";
            message.Html = "file attachment test<br /><img src=\"cid:hogehoge\" /><br />inline image";

            message.AddAttachment(ConfigurationManager.AppSettings["AttachmentImage"], "maki.jpg");
            message.Content.Add("maki.jpg", "hogehoge");

            client.Send(message);
        }