Exemplo n.º 1
0
        internal static Mail AddAttachments(Mail message, string[] attachments)
        {
            if (attachments != null)
            {
                foreach (string file in attachments)
                {
                    if (!string.IsNullOrWhiteSpace(file))
                    {
                        if (File.Exists(file))
                        {
                            using (var stream = new FileStream(file, FileMode.Open))
                            {
                                using (var reader = new StreamReader(stream))
                                {
                                    string fileName = new FileInfo(file).Name;

                                    var attachment = new Attachment
                                    {
                                        Filename    = fileName,
                                        Content     = reader.ReadToEnd(),
                                        Type        = MimeMapping.GetMimeMapping(file),
                                        Disposition = "attachment",
                                        ContentId   = fileName
                                    };

                                    message.AddAttachment(attachment);
                                }
                            }
                        }
                    }
                }
            }

            return(message);
        }
Exemplo n.º 2
0
        // this code is used for the SMTPAPI examples
        static void Main(string[] args)
        {
            // Create the email object first, then add the properties.
            Mail myMessage = Mail.GetInstance();

            myMessage.AddTo("*****@*****.**");
            myMessage.From    = new MailAddress("*****@*****.**", "John Smith");
            myMessage.Subject = "Testing the SendGrid Library";
            myMessage.Text    = "Hello World!";
            myMessage.Html    = "<html><body><p>Hello World</p><img src=\"cid:img1\"/></body></html>";

            var imgStream = System.IO.File.OpenRead(@"img_test.png");

            myMessage.AddAttachment(imgStream, "img_test.png", "image/png", "img1");

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

            // Create a Web transport for sending email.
            var transportWeb = Web.GetInstance(credentials);

            // Send the email.
            transportWeb.DeliverAsync(myMessage);

            Console.WriteLine("Done!");
            Console.ReadLine();
        }
Exemplo n.º 3
0
        internal static Mail AddAttachments(Mail message, string[] attachments)
        {
            if (attachments == null)
            {
                return(message);
            }

            foreach (string file in attachments)
            {
                if (string.IsNullOrWhiteSpace(file) || !File.Exists(file))
                {
                    continue;
                }

                var    bytes   = File.ReadAllBytes(file);
                string content = Convert.ToBase64String(bytes);

                string fileName = new FileInfo(file).Name;

                var attachment = new Attachment
                {
                    Filename    = fileName,
                    Content     = content,
                    Type        = MimeMapping.GetMimeMapping(file),
                    Disposition = "attachment",
                    ContentId   = fileName
                };

                message.AddAttachment(attachment);
            }

            return(message);
        }
Exemplo n.º 4
0
        private static void AddAttachment(this Mail mail, string filename, string content)
        {
            var bytes         = Encoding.ASCII.GetBytes(content);
            var base64Content = Convert.ToBase64String(bytes);

            var attachment = new Attachment
            {
                Filename = filename,
                Content  = base64Content
            };

            mail.AddAttachment(attachment);
        }
        public void TestAddAttachment()
        {
            var foo = new Mock<IHeader>();
            var sg = new Mail(foo.Object);

            //var data = new Attachment("pnunit.framework.dll", MediaTypeNames.Application.Octet);
            sg.AddAttachment("pnunit.framework.dll");
            sg.AddAttachment("pnunit.framework.dll");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.First().ContentStream, "Attach via path");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.Skip(1).First().ContentStream, "Attach via path x2");

            sg = new Mail(foo.Object);
            //sg.AddAttachment(data);
            //sg.AddAttachment(data);
            //Assert.AreEqual(data.ContentStream, sg.Attachments.First().ContentStream, "Attach via attachment");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.Skip(1).First().ContentStream, "Attach via attachment x2");

            sg = new Mail(foo.Object);
            //sg.AddAttachment(data.ContentStream, data.ContentType);
            //sg.AddAttachment(data.ContentStream, data.ContentType);
            //Assert.AreEqual(data.ContentStream, sg.Attachments.First().ContentStream, "Attach via stream");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.Skip(1).First().ContentStream, "Attach via stream x2");
        }
        public void TestAddAttachment()
        {
            var foo = new Mock <IHeader>();
            var sg  = new Mail(foo.Object);

            //var data = new Attachment("pnunit.framework.dll", MediaTypeNames.Application.Octet);
            sg.AddAttachment("pnunit.framework.dll");
            sg.AddAttachment("pnunit.framework.dll");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.First().ContentStream, "Attach via path");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.Skip(1).First().ContentStream, "Attach via path x2");

            sg = new Mail(foo.Object);
            //sg.AddAttachment(data);
            //sg.AddAttachment(data);
            //Assert.AreEqual(data.ContentStream, sg.Attachments.First().ContentStream, "Attach via attachment");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.Skip(1).First().ContentStream, "Attach via attachment x2");

            sg = new Mail(foo.Object);
            //sg.AddAttachment(data.ContentStream, data.ContentType);
            //sg.AddAttachment(data.ContentStream, data.ContentType);
            //Assert.AreEqual(data.ContentStream, sg.Attachments.First().ContentStream, "Attach via stream");
            //Assert.AreEqual(data.ContentStream, sg.Attachments.Skip(1).First().ContentStream, "Attach via stream x2");
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get a mail object to sendgrid
        /// </summary>
        private static Mail PrepareSendGridMessage(MessageCredential credential, MessageSend message)
        {
            Personalization personalizacion = new Personalization();

            foreach (var mailto in message.MailTo)
            {
                personalizacion.AddTo(new Email(mailto));
            }

            foreach (var ccp in message.CCP)
            {
                personalizacion.AddCc(new Email(ccp));
            }

            foreach (var cco in message.CCO)
            {
                personalizacion.AddBcc(new Email(cco));
            }

            Mail mail = new Mail();

            mail.From = new Email(credential.UserName, credential.DisplayName);

            mail.Subject    = message.Subject;
            mail.CustomArgs = message.Args;

            foreach (var attachment in message.Attachment)
            {
                Byte[] bytes = File.ReadAllBytes(attachment);

                mail.AddAttachment(new SendGrid.Helpers.Mail.Attachment()
                {
                    Filename = Path.GetFileName(attachment), Content = Convert.ToBase64String(bytes)
                });

                bytes = null;
            }

            mail.AddContent(new Content("text/html", message.Body));
            mail.AddPersonalization(personalizacion);

            return(mail);
        }
Exemplo n.º 8
0
        private void AddAttachments(EmailCommunication email, Mail mail)
        {
            if (email.Attachments != null)
            {
                foreach (string filePath in email.Attachments)
                {
                    string fileContents = Convert.ToBase64String(File.ReadAllBytes(filePath));

                    string contentType = "application/octet-stream";
                    //new FileExtensionContentTypeProvider().TryGetContentType(filePath, out contentType);
                    //contentType = contentType ?? "application/octet-stream";

                    Attachment attachment = new Attachment();
                    attachment.Content     = fileContents;
                    attachment.Type        = contentType;
                    attachment.Filename    = Path.GetFileName(filePath);
                    attachment.Disposition = "attachment";
                    mail.AddAttachment(attachment);
                }
            }
        }
Exemplo n.º 9
0
        public void FurtherOrderStatus(int _orderID, OrderStatus.OrderStatusesEnum _orderStatus, string _DCMSG)
        {
            string notificationMsg         = "";
            var    identity                = (ClaimsIdentity)User.Identity;
            int    notificationRecipientID = 0;

            try
            {
                IOrderRepository OrderRepo = new OrderRepository();
                Order            Order     = OrderRepo.GetOrderByID(_orderID);
                if (Order.Products.Count > 0)
                {
                    if (Order.Statuses.FindIndex(x => x.RegisteredStatus == _orderStatus) == -1)
                    {
                        foreach (string str in OrderRepo.FurtherOrderStatus(Order, _orderStatus))
                        {
                            notificationMsg += str;
                        }
                    }
                    if (_orderStatus == OrderStatus.OrderStatusesEnum.WaitingForDC)
                    {
                        UpdateOrderOverviewTroughSignalR();
                        var          body = System.IO.File.ReadAllText(Server.MapPath(@"~\Content\EmailTemplate.cshtml"));
                        Mail         mail = new Mail("*****@*****.**", "Nieuwe Bestelling: " + Order.ID + " van: " + Order.Customer.Name, string.Format(body, Order.Customer.ID, DateTime.Now.ToString("dd/MM/yyyy")));
                        MemoryStream strm = new MemoryStream(((ViewAsPdf)GetPDFPackingSlip(Order)).BuildFile(ControllerContext));
                        System.Net.Mail.Attachment pdfatt = new System.Net.Mail.Attachment(strm, "Bestelling: " + Order.ID + ".pdf", "application/pdf");
                        if (Convert.ToInt16(identity.Claims.Last().Value) != Order.Customer.ID)
                        {
                            notificationRecipientID = Convert.ToInt16(identity.Claims.Last().Value);
                        }
                        else
                        {
                            notificationRecipientID = Order.Customer.ID;
                            SendMessageTroughSignalR(8, Order.Customer.Name + " Heeft een nieuwe bestelling doorgevoerd");
                        }
                        SendMessageTroughSignalR(notificationRecipientID, notificationMsg);
                        mail.AddAttachment(pdfatt);
                        mail.SendMail();
                    }
                    else if (_orderStatus == OrderStatus.OrderStatusesEnum.Processing)
                    {
                        UpdateOrderOverviewTroughSignalR();
                        SendMessageTroughSignalR(Convert.ToInt16(identity.Claims.Last().Value), string.Format("Bestelling: {0} in behandeling genomen", _orderID));
                    }
                    else if (_orderStatus == OrderStatus.OrderStatusesEnum.Delivered)
                    {
                        UpdateOrderOverviewTroughSignalR();
                        SendMessageTroughSignalR(Convert.ToInt16(identity.Claims.Last().Value), string.Format("Bestelling: {0} succesvol verwerkt", _orderID));
                    }
                    else if (_orderStatus == OrderStatus.OrderStatusesEnum.Rejected)
                    {
                        UpdateOrderOverviewTroughSignalR();
                        SendMessageTroughSignalR(Order.Customer.ID, string.Format("Distributie Centrum heeft uw bestelling: {0} geweigerd. Melding van DC: {1}", _orderID, _DCMSG));
                        SendMessageTroughSignalR(Convert.ToInt16(identity.Claims.Last().Value), notificationMsg);
                    }
                }
                else
                {
                    SendMessageTroughSignalR(Convert.ToInt16(identity.Claims.Last().Value), "Geen Producten in bestelling");
                }
            }
            catch
            {
                SendMessageTroughSignalR(Convert.ToInt16(identity.Claims.Last().Value), "Er ging iets fout tijdens het verwerken van de bestelling!");
            }
        }
        public static async Task Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req,
            [Table("UserProfile")] CloudTable userProfileTable,
            [Queue("emaillogqueue")] CloudQueue queue,
            IBinder binder,
            [SendGrid()] IAsyncCollector <Mail> message,
            [TwilioSms()] IAsyncCollector <SMSMessage> smsMessage,
            TraceWriter log)
        {
            try
            {
                log.Info($"RegisterUserAndSendSms function processed a request.");

                var user = JsonConvert.DeserializeObject <UserProfile>(await req.Content.ReadAsStringAsync());
                if (user == null)
                {
                    throw new System.Exception("Please provide values for First name,Last Name and Profile Picture");
                }
                var userProfile = new UserProfile(user.FirstName, user.LastName, user.ProfilePicture, user.Email);

                var tblInsertOperation = TableOperation.Insert(userProfile);
                var insertResult       = await userProfileTable.ExecuteAsync(tblInsertOperation);

                var insertedUser = (UserProfile)insertResult.Result;

                var mail = new Mail
                {
                    Subject = $"Thanks {userProfile.FirstName} {userProfile.LastName} for your Sign Up!"
                };

                var personalization = new Personalization();
                personalization.AddTo(new Email(userProfile.Email));

                Content content = new Content
                {
                    Type  = "text/plain",
                    Value = $"{userProfile.FirstName}, here's the link for your profile picture {userProfile.ProfilePicture}!"
                };

                await queue.AddMessageAsync(new CloudQueueMessage(content.Value.ToString()));

                var queueMessage = await queue.GetMessageAsync();

                var data = queueMessage.AsString;
                using (var emailLogBlob = binder.Bind <TextWriter>(new BlobAttribute($"emailogblobcontainer/{insertedUser.RowKey}.log")))
                {
                    await emailLogBlob.WriteAsync(data);
                }

                var attachment = new Attachment();
                attachment.Content  = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(data));
                attachment.Filename = $"{insertedUser.FirstName}_{insertedUser.LastName}.log";
                mail.AddAttachment(attachment);
                mail.AddContent(content);
                mail.AddPersonalization(personalization);
                await message.AddAsync(mail);

                //SMS Code
                var sms = new SMSMessage();
                sms.To   = "XXXXXXXXXXXXXXX";
                sms.From = System.Configuration.ConfigurationManager.AppSettings["AzureWebJobsFromNumber"];
                sms.Body = "How is it going!";

                await smsMessage.AddAsync(sms);
            }
            catch (System.Exception ex)
            {
                log.Info($"RegisterUserAndSendSms function : Exception:{ ex.Message}");
                throw;
            }
            finally
            {
                log.Info("RegisterUserAndSendSms function has finished processing a request.");
            }
        }
Exemplo n.º 11
0
        private static void KitchenSink()
        {
            String  apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
            dynamic sg     = new SendGrid.SendGridAPIClient(apiKey, "https://api.sendgrid.com");

            Mail mail = new Mail();

            Email email = new Email();

            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            mail.From     = email;

            mail.Subject = "Hello World from the SendGrid CSharp Library";

            Personalization personalization = new Personalization();

            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddTo(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            personalization = new Personalization();
            email           = new Email();
            email.Name      = "Example User";
            email.Address   = "*****@*****.**";
            personalization.AddTo(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddCc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            email         = new Email();
            email.Name    = "Example User";
            email.Address = "*****@*****.**";
            personalization.AddBcc(email);
            personalization.Subject = "Thank you for signing up, %name%";
            personalization.AddHeader("X-Test", "True");
            personalization.AddHeader("X-Mock", "True");
            personalization.AddSubstitution("%name%", "Example User");
            personalization.AddSubstitution("%city%", "Denver");
            personalization.AddCustomArgs("marketing", "false");
            personalization.AddCustomArgs("transactional", "true");
            personalization.SendAt = 1461775051;
            mail.AddPersonalization(personalization);

            Content content = new Content();

            content.Type  = "text/plain";
            content.Value = "Textual content";
            mail.AddContent(content);
            content       = new Content();
            content.Type  = "text/html";
            content.Value = "<html><body>HTML content</body></html>";
            mail.AddContent(content);
            content       = new Content();
            content.Type  = "text/calendar";
            content.Value = "Party Time!!";
            mail.AddContent(content);

            Attachment attachment = new Attachment();

            attachment.Content     = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12";
            attachment.Type        = "application/pdf";
            attachment.Filename    = "balance_001.pdf";
            attachment.Disposition = "attachment";
            attachment.ContentId   = "Balance Sheet";
            mail.AddAttachment(attachment);

            attachment             = new Attachment();
            attachment.Content     = "BwdW";
            attachment.Type        = "image/png";
            attachment.Filename    = "banner.png";
            attachment.Disposition = "inline";
            attachment.ContentId   = "Banner";
            mail.AddAttachment(attachment);

            mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932";

            mail.AddHeader("X-Day", "Monday");
            mail.AddHeader("X-Month", "January");

            mail.AddSection("%section1", "Substitution for Section 1 Tag");
            mail.AddSection("%section2", "Substitution for Section 2 Tag");

            mail.AddCategory("customer");
            mail.AddCategory("vip");

            mail.AddCustomArgs("campaign", "welcome");
            mail.AddCustomArgs("sequence", "2");

            ASM asm = new ASM();

            asm.GroupId = 3;
            List <int> groups_to_display = new List <int>()
            {
                1, 4, 5
            };

            asm.GroupsToDisplay = groups_to_display;
            mail.Asm            = asm;

            mail.SendAt = 1461775051;

            mail.SetIpPoolId = "23";

            // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html)
            // mail.BatchId = "some_batch_id";

            MailSettings mailSettings = new MailSettings();
            BCCSettings  bccSettings  = new BCCSettings();

            bccSettings.Enable       = true;
            bccSettings.Email        = "*****@*****.**";
            mailSettings.BccSettings = bccSettings;
            BypassListManagement bypassListManagement = new BypassListManagement();

            bypassListManagement.Enable       = true;
            mailSettings.BypassListManagement = bypassListManagement;
            FooterSettings footerSettings = new FooterSettings();

            footerSettings.Enable       = true;
            footerSettings.Text         = "Some Footer Text";
            footerSettings.Html         = "<bold>Some HTML Here</bold>";
            mailSettings.FooterSettings = footerSettings;
            SandboxMode sandboxMode = new SandboxMode();

            sandboxMode.Enable       = true;
            mailSettings.SandboxMode = sandboxMode;
            SpamCheck spamCheck = new SpamCheck();

            spamCheck.Enable       = true;
            spamCheck.Threshold    = 1;
            spamCheck.PostToUrl    = "https://gotchya.example.com";
            mailSettings.SpamCheck = spamCheck;
            mail.MailSettings      = mailSettings;

            TrackingSettings trackingSettings = new TrackingSettings();
            ClickTracking    clickTracking    = new ClickTracking();

            clickTracking.Enable           = true;
            clickTracking.EnableText       = false;
            trackingSettings.ClickTracking = clickTracking;
            OpenTracking openTracking = new OpenTracking();

            openTracking.Enable           = true;
            openTracking.SubstitutionTag  = "Optional tag to replace with the open image in the body of the message";
            trackingSettings.OpenTracking = openTracking;
            SubscriptionTracking subscriptionTracking = new SubscriptionTracking();

            subscriptionTracking.Enable           = true;
            subscriptionTracking.Text             = "text to insert into the text/plain portion of the message";
            subscriptionTracking.Html             = "<bold>HTML to insert into the text/html portion of the message</bold>";
            subscriptionTracking.SubstitutionTag  = "text to insert into the text/plain portion of the message";
            trackingSettings.SubscriptionTracking = subscriptionTracking;
            Ganalytics ganalytics = new Ganalytics();

            ganalytics.Enable           = true;
            ganalytics.UtmCampaign      = "some campaign";
            ganalytics.UtmContent       = "some content";
            ganalytics.UtmMedium        = "some medium";
            ganalytics.UtmSource        = "some source";
            ganalytics.UtmTerm          = "some term";
            trackingSettings.Ganalytics = ganalytics;
            mail.TrackingSettings       = trackingSettings;

            email         = new Email();
            email.Address = "*****@*****.**";
            mail.ReplyTo  = email;

            String ret = mail.Get();

            string  requestBody = ret;
            dynamic response    = sg.client.mail.send.post(requestBody: requestBody);

            Console.WriteLine(response.StatusCode);
            Console.WriteLine(response.Body.ReadAsStringAsync().Result);
            Console.WriteLine(response.Headers.ToString());

            Console.WriteLine(ret);
            Console.ReadLine();
        }
Exemplo n.º 12
0
Arquivo: Mails.cs Projeto: pyla786/ddd
 public bool SendInvoice(string subject, string body, string description, List <string> toEmail, string FileBase64String, string Fromemail, string Filename, List <Email> CCs)
 {
     try
     {
         long          emailsentcount = 0;
         bool          issucceeded    = false;
         List <string> uniqueemails   = new List <string>();
         string        sendGridApi    = Literals.SendGridApiKey;
         string        outgoingEmail  = Fromemail;
         dynamic       sg             = new SendGridAPIClient(sendGridApi);
         Email         from           = new Email(outgoingEmail);
         Content       bodycontent;
         if (!string.IsNullOrEmpty(description))
         {
             bodycontent = new Content("text/html", body.ToString() + "<br/><br/>" + description);
         }
         else
         {
             bodycontent = new Content("text/html", body.ToString());
         }
         string Contenttype = "application/pdf";
         var    attachment  = new Attachment
         {
             Filename = Filename,
             Type     = Contenttype,
             Content  = FileBase64String
         };
         foreach (var toemail in toEmail)
         {
             Email to   = new Email(toemail);
             Mail  mail = new Mail(from, subject, to, bodycontent);
             mail.AddAttachment(attachment);
             if (CCs != null && CCs.Count() > 0)
             {
                 uniqueemails.AddRange(toEmail);
                 var personalization = new Personalization();
                 for (var i = 0; i < CCs.Count(); i++)
                 {
                     if (!uniqueemails.Contains(CCs[i].Address))
                     {
                         uniqueemails.Add(CCs[i].Address);
                         mail.Personalization[0].AddCc(CCs[i]);
                     }
                 }
             }
             SendGrid.CSharp.HTTP.Client.Response response = sg.client.mail.send.post(requestBody: mail.Get());
             if (response.StatusCode == System.Net.HttpStatusCode.Accepted)
             {
                 emailsentcount++;
             }
             else
             {
                 int ErrorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
                 var Request   = System.Web.HttpContext.Current.Request;
             }
         }
         if (emailsentcount == toEmail.Count())
         {
             issucceeded = true;
         }
         return(issucceeded);
     }
     catch (Exception ex)
     {
         int ErrorCode = System.Runtime.InteropServices.Marshal.GetLastWin32Error();
         var Request   = System.Web.HttpContext.Current.Request;
         //Methods.Errorlog(ex.Message, "Send Grid", ErrorCode, Request.Url.AbsolutePath, null, userTypeId);
         return(false);
     }
 }