コード例 #1
0
        /// <summary>
        /// Sending Email through Mandril API (Using Mandril Templates)
        /// </summary>
        /// <param name="fromEmail"></param>
        /// <param name="fromName"></param>
        /// <param name="toMails"></param>
        /// <param name="subject"></param>
        /// <param name="templateName"></param>
        /// <param name="MergeVariables"></param>
        /// <returns></returns>
        public static List <EmailResult> SendMail(string fromEmail, string fromName, List <string> toMails, string subject, string templateName, Dictionary <string, dynamic> MergeVariables)
        {
            try
            {
                var api = new MandrillApi(Config.Key);

                var email = new EmailMessage()
                {
                    FromEmail = fromEmail,
                    FromName  = fromName,
                    Subject   = subject,
                };
                email.Merge         = true;
                email.MergeLanguage = "mailchimp";
                //email.Headers.Add("Reply-To", "*****@*****.**");

                foreach (var item in MergeVariables)
                {
                    email.AddGlobalVariable(item.Key, item.Value);
                }


                var to = toMails.Select(mailTo => new EmailAddress(mailTo)).ToList();
                email.To = to;

                // Send email
                var smReq  = new SendMessageTemplateRequest(email, templateName);
                var output = api.SendMessageTemplate(smReq).Result;
                return(output);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #2
0
ファイル: EmailSender.cs プロジェクト: LasVegasIs/TestingYAML
        public async Task SendEmailTemplateAsync(string emailAddress, string template, Dictionary <string, string> templateParameters)
        {
            var emailMessage = new EmailMessage();

            emailMessage.To = new[] { new EmailAddress(emailAddress) };

            foreach (var item in templateParameters)
            {
                emailMessage.AddGlobalVariable(item.Key, item.Value);
            }

            var messageTemplateRequest      = new SendMessageTemplateRequest(emailMessage, template);
            List <EmailResult> emailResults = await mandrillApi_.SendMessageTemplate(messageTemplateRequest);

            foreach (var item in emailResults)
            {
                if (item.Status == EmailResultStatus.Rejected)
                {
                    throw new ServerErrorException(
                              $"Sending email template {template} to {item.Email} with parameters: {string.Join(",", templateParameters)} failed with reason: {item.RejectReason}");
                }

                if (item.Status == EmailResultStatus.Invalid)
                {
                    throw new InvalidArgumentException(
                              $"Sending email template {template} to {item.Email} with parameters: {string.Join(",", templateParameters)} is invalid");
                }
            }
        }
コード例 #3
0
        public bool Send(string targetEmail, Dictionary <string, string> payload, EmailType emailType, byte[] byteArray)
        {
            List <EmailAddress> toEmailAddresses = new List <EmailAddress>();
            //List<TemplateContent> contents = new List<TemplateContent>();

            EmailAddress toEmailAddress = new EmailAddress();

            toEmailAddress.email = targetEmail;

            toEmailAddresses.Add(toEmailAddress);

            if (payload.TryGetValue("cc", out _ccAddress))
            {
                EmailAddress ccEmailAddress = new EmailAddress();
                ccEmailAddress.email = _ccAddress;
                ccEmailAddress.type  = "cc";

                toEmailAddresses.Add(ccEmailAddress);
            }

            EmailMessage emailMessage = new EmailMessage();

            emailMessage.to = toEmailAddresses;
            if (payload.TryGetValue("subject", out _subject))
            {
                emailMessage.subject = _subject;
            }
            emailMessage.attachments = new List <email_attachment>();
            email_attachment mailAttachment = new email_attachment();

            mailAttachment.content = Convert.ToBase64String(byteArray);
            mailAttachment.name    = payload["AttachFileName"];//"PaymentLinkRequest.csv";
            mailAttachment.type    = payload["AttachFileType"];
            ((List <email_attachment>)emailMessage.attachments).Add(mailAttachment);

            emailMessage.merge = true;

            foreach (KeyValuePair <string, string> templateContent in payload)
            {
                emailMessage.AddGlobalVariable(templateContent.Key, templateContent.Value);
            }

            //  emailMessage.from_email = FromAddress;
            //  emailMessage.subject = "Test";
            List <EmailResult> results = _api.SendMessage(emailMessage, GetTemplateName(emailType), null);


            if (results.Count > 0)
            {
                foreach (EmailResult result in results)
                {
                    if (result.Status == EmailResultStatus.Sent || result.Status == EmailResultStatus.Queued)
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #4
0
ファイル: EmailHelper.cs プロジェクト: windygu/Maxikioscos
        public static List <EmailResult> SendMailTemplate(List <string> toMails, string templateName, List <merge_var> mergeVars, string subject)
        {
            try
            {
                var api = new MandrillApi(_mandrillApiKey);

                var email = new EmailMessage
                {
                    from_email = _senderEmail,
                    subject    = subject
                };

                var to = toMails.Select(mailTo => new EmailAddress(mailTo)).ToList();

                email.to = to;
                foreach (merge_var item in mergeVars)
                {
                    email.AddGlobalVariable(item.name, item.content);
                }

                var result = api.SendMessageAsync(email, templateName, null);
                return(result.Result);
            }
            catch (Exception ex)
            {
                EventLogger.Log(ex);
                return(null);
                //ManagementBLL.LogError("SendMailMandrill", ex.Message, "EmailHelper", string.Empty);
            }
        }
コード例 #5
0
    public static void SendWelcomeEmail(string emailAddress, string userName)
    {
        string apiKey = ConfigurationManager.AppSettings["MandrillAPIKey"];

        var api = new MandrillApi(apiKey);

        var recipients = new List <EmailAddress>();

        recipients.Add(new EmailAddress(emailAddress, userName));


        var message = new EmailMessage()
        {
            to         = recipients,
            from_email = "*****@*****.**",
            from_name  = "Cult Collection",
            subject    = "Welcome to Cult Collection",
        };

        message.AddGlobalVariable("FNAME", userName);
        message.important = true;

        var result = api.SendMessageAsync(message, "Welcome Email 1st", null);

        try
        {
            SubscribeUserToMailChimp(emailAddress, userName);
        }
        catch (Exception) { }
    }
コード例 #6
0
    public static void SendWelcomeEmailv2(string emailAddress, UserProfile user, string userAgent, string db)
    {
        string apiKey = ConfigurationManager.AppSettings["MandrillAPIKey"];

        var api = new MandrillApi(apiKey);

        var recipients = new List <EmailAddress>();

        recipients.Add(new EmailAddress(emailAddress, user.userName));


        var message = new EmailMessage()
        {
            to         = recipients,
            from_email = "*****@*****.**",
            from_name  = "Cult Collection",
            subject    = "Welcome to Cult Collection",
        };

        message.AddGlobalVariable("FNAME", user.userName);

        //Get Hot itema

        /*
         * List<Product> hotItems = Product.GetPopularProductsByUserv2(user.userId, db, 1, 6);
         * for (int i=1; i<= hotItems.Count(); i++)
         * {
         *  message.AddGlobalVariable("II"+i, hotItems[i-1].GetNormalImageUrl());
         *  message.AddGlobalVariable("IN"+i, hotItems[i-1].name);
         *  message.AddGlobalVariable("IB" + i, hotItems[i-1].brandName);
         *  message.AddGlobalVariable("IU" + i, "http://startcult.com/product.html?prodId=" + hotItems[i - 1].id + "&colorId=" + hotItems[i - 1].colors[0].canonical[0]
         + "&catId=" + hotItems[i - 1].categories[0] + "&user=CultCollection&url=" );
         + }
         */

        message.important = true;

        if (userAgent.Contains("iPad"))
        {
            var result = api.SendMessageAsync(message, "Welcome basic – iPad", null);
        }
        else if (userAgent.Contains("iPhone"))
        {
            var result = api.SendMessageAsync(message, "Welcome basic – iPhone", null);
        }

        try
        {
            //SubscribeUserToMailChimp(emailAddress, user.userName);
        }
        catch (Exception) { }
    }
コード例 #7
0
        private void AddUnsubLinkToEmail(string unsubEmail, EmailMessage email)
        {
            var unsubUriBuilder = new UriBuilder(Consts.SiteUrl);

            unsubUriBuilder.Path = "/settings";

            var values = HttpUtility.ParseQueryString(string.Empty);

            values["email"]       = unsubEmail;
            unsubUriBuilder.Query = values.ToString();

            email.AddGlobalVariable("UNSUB_LINK", unsubUriBuilder.Uri.ToString());
        }
コード例 #8
0
        public Task SendResetPasswordEmail(string firstName, string email, string resetLink)
        {
            const string subject = "Reset My Notes Password Request";

            var emailMessage = new EmailMessage
            {
                from_email = EmailFromAddress,
                from_name  = EmailFromName,
                subject    = subject,
                to         = new List <Mandrill.EmailAddress> {
                    new EmailAddress(email)
                }
            };

            emailMessage.AddGlobalVariable("subject", subject);
            emailMessage.AddGlobalVariable("FIRST_NAME", firstName);
            emailMessage.AddGlobalVariable("RESET_PASSWORD_LINK", resetLink);

            var task = _mandrill.SendMessageAsync(emailMessage, "reset-password-notes-saas", null);

            return(task);
        }
コード例 #9
0
        public Task SendWelcomeEmail(string firstName, string email)
        {
            const string subject = "Welcome to My Notes";

            var emailMessage = new EmailMessage
            {
                from_email = EmailFromAddress,
                from_name  = EmailFromName,
                subject    = subject,
                to         = new List <Mandrill.EmailAddress> {
                    new EmailAddress(email)
                },
                merge = true,
            };

            emailMessage.AddGlobalVariable("subject", subject);
            emailMessage.AddGlobalVariable("FIRST_NAME", firstName);

            var task = _mandrill.SendMessageAsync(emailMessage, "welcome-my-notes-saas", null);

            task.Wait();

            return(task);
        }
コード例 #10
0
        public Task SendWelcomeEmail(string firstName, string email)
        {
            const string subject = "Bienvenue dans eTransfert";

            var emailMessage = new EmailMessage
            {
                FromEmail = EmailFromAddress,
                FromName  = EmailFromName,
                Subject   = subject,
                To        = new List <Mandrill.Models.EmailAddress> {
                    new EmailAddress(email)
                },
                Merge = true,
            };

            emailMessage.AddGlobalVariable("subject", subject);
            emailMessage.AddGlobalVariable("first_name", firstName);

            var task = _mandrill.SendMessageTemplate(new SendMessageTemplateRequest(emailMessage, "welcome_chimp", null));

            task.Wait();

            return(task);
        }
コード例 #11
0
        public bool Send(string targetEmail, Dictionary <string, string> payload, EmailType emailType, List <email_attachment> attachmentList = null)
        {
            try
            {
                List <EmailAddress> toEmailAddresses = new List <EmailAddress>();
                //List<TemplateContent> contents = new List<TemplateContent>();

                EmailAddress toEmailAddress = new EmailAddress();
                toEmailAddress.email = targetEmail;

                toEmailAddresses.Add(toEmailAddress);

                if (payload.TryGetValue("cc", out _ccAddress))
                {
                    EmailAddress ccEmailAddress = new EmailAddress();
                    ccEmailAddress.email = _ccAddress;
                    ccEmailAddress.type  = "cc";

                    toEmailAddresses.Add(ccEmailAddress);
                }

                EmailMessage emailMessage = new EmailMessage();
                emailMessage.to = toEmailAddresses;

                emailMessage.merge = true;

                foreach (KeyValuePair <string, string> templateContent in payload)
                {
                    emailMessage.AddGlobalVariable(templateContent.Key, templateContent.Value);
                }

                if (payload.TryGetValue("from", out _fromAddress))
                {
                    emailMessage.from_email = _fromAddress;
                }
                if (payload.TryGetValue("from_name", out _displayName))
                {
                    emailMessage.from_name = _displayName;
                }
                if (payload.TryGetValue("subject", out _subject))
                {
                    emailMessage.subject = _subject;
                }

                if (attachmentList != null && attachmentList.Count > 0)
                {
                    emailMessage.attachments = attachmentList;
                }

                //emailMessage.from_email = "*****@*****.**";
                //emailMessage.subject = "Test";

                List <EmailResult> results = _api.SendMessage(emailMessage, GetTemplateName(emailType), null);


                if (results.Count > 0)
                {
                    foreach (EmailResult result in results)
                    {
                        if (result.Status == EmailResultStatus.Sent || result.Status == EmailResultStatus.Queued)
                        {
                            return(true);
                        }
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex);

                return(false);
            }
        }
コード例 #12
0
        public ActionResult SendInvitation(InvitationModel model)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand("insert into emailtofriends(name, email, message) values (@name, @email, @message)", connection);
                command.Parameters.AddWithValue("name", model.Name);
                command.Parameters.AddWithValue("email", model.Email);
                command.Parameters.AddWithValue("message", model.Message);

                try
                {
                    command.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    // do what?

                }
                finally
                {
                    connection.Close();
                }

                //Send mandril message
                try
                {
                    MandrillApi api = new MandrillApi(ProjectConfiguration.MandrillApiKey);
                    var emailMessage = new EmailMessage()
                    {
                        To = new List<EmailAddress>() { new EmailAddress(model.Email, "Invited") },
                        FromEmail = ProjectConfiguration.FromEmail,
                        FromName = ProjectConfiguration.FromName,
                        Subject = string.Format(ProjectConfiguration.InvitationEmailSubject, model.Name),
                        Merge = true,
                        MergeLanguage = "mailchimp"
                    };

                    emailMessage.AddGlobalVariable("invitername", model.Name);
                    emailMessage.AddGlobalVariable("invitermessage", model.Message.Replace("\n", "<br />"));

                    var request = new SendMessageTemplateRequest(emailMessage, "invitation", null);
                    var result = api.SendMessageTemplate(request);
                }
                catch (Exception ex)
                {
                    // do what?
                }

                return new EmptyResult();
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: Fashionkred/ShopSenseDemo
        public static void SendRetentionEmail(string templateName, string subject, int days, string userAgent = "iPad")
        {
            List <string> usernames = new List <string>();
            List <string> emails    = new List <string>();
            string        query     = "";

            switch (days)
            {
            case 1:
                query = "EXEC [stp_SS_Retention1d]";
                break;

            case 2:
                query = "EXEC [stp_SS_Retention2d] ";
                break;

            case 3:
                query = "EXEC [stp_SS_Retention3d] @userAgent='" + userAgent + "'";
                break;

            case 4:
                query = "EXEC [stp_SS_Retention4d] ";
                break;

            case 7:
                query = "EXEC [stp_SS_Retention7d] ";
                break;
            }

            SqlConnection myConnection = new SqlConnection(db);

            try
            {
                myConnection.Open();
                using (SqlDataAdapter adp = new SqlDataAdapter(query, myConnection))
                {
                    SqlCommand cmd = adp.SelectCommand;
                    cmd.CommandTimeout = 300000;
                    System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        string username = dr["username"].ToString();
                        string email    = dr["email"].ToString();
                        //string email = "*****@*****.**";

                        usernames.Add(username);
                        emails.Add(email);
                    }
                }
            }
            finally
            {
                myConnection.Close();
            }

            var api = new MandrillApi(apiKey);

            for (int i = 0; i < usernames.Count(); i++)
            {
                var recipients = new List <EmailAddress>();
                recipients.Add(new EmailAddress(emails[i], usernames[i]));


                var message = new EmailMessage()
                {
                    to         = recipients,
                    from_email = "*****@*****.**",
                    from_name  = "Cult Collection",
                    subject    = subject,
                };
                message.AddGlobalVariable("FNAME", usernames[i]);

                var result = api.SendMessage(message, templateName, null);
                //result.
            }
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: Fashionkred/ShopSenseDemo
        public static void SendDigestEmail()
        {
            List <string> usernames = new List <string>();
            List <string> emails    = new List <string>();
            List <long>   userIds   = new List <long>();

            List <EmailTemplate> eligibleTemplate = GetEligibleTemplates();

            if (eligibleTemplate.Count == 0)
            {
                return;
            }

            string query = "EXEC [stp_SS_WeekDigest] ";

            SqlConnection myConnection = new SqlConnection(db);

            try
            {
                myConnection.Open();
                using (SqlDataAdapter adp = new SqlDataAdapter(query, myConnection))
                {
                    SqlCommand cmd = adp.SelectCommand;
                    cmd.CommandTimeout = 300000;
                    System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        string username = dr["username"].ToString();
                        string email    = dr["email"].ToString();
                        //string email = "*****@*****.**";
                        long id = long.Parse(dr["id"].ToString());

                        usernames.Add(username);
                        emails.Add(email);
                        userIds.Add(id);
                    }
                }
            }
            finally
            {
                myConnection.Close();
            }

            var api = new MandrillApi(apiKey);

            foreach (EmailTemplate t in eligibleTemplate)
            {
                List <Look> featuredLooks = new List <Look>();
                List <Look> topLooks      = new List <Look>();
                List <Tag>  featuredTags  = new List <Tag>();

                if (t.templateName == "Weekly Consumption Email" || t.templateName == "Weekly Consumption Email with Editorial")
                {
                    string tagName = string.Empty;
                    if (t.tags.Count > 0)
                    {
                        tagName = t.tags[0];
                    }

                    featuredLooks = SendEmailToFeaturedLookCreator(t.lookIds, tagName);
                }
                else if (t.templateName == "Weekly Content Email")
                {
                    topLooks = Look.GetPopularLooksOfWeek(db, 1, 1, 3);
                    if (t.tags.Count > 0)
                    {
                        for (int tt = 1; tt <= t.tags.Count; tt++)
                        {
                            Tag tag = Tag.GetTagByName(t.tags[tt - 1], 0, db);
                            featuredTags.Add(tag);
                        }
                    }
                }

                for (int i = 0; i < usernames.Count(); i++)
                {
                    var recipients = new List <EmailAddress>();
                    recipients.Add(new EmailAddress(emails[i], usernames[i]));


                    var message = new EmailMessage()
                    {
                        to         = recipients,
                        from_email = "*****@*****.**",
                        from_name  = "Cult Collection",
                        subject    = t.subject,
                    };
                    message.AddGlobalVariable("FNAME", usernames[i]);
                    message.AddGlobalVariable("EH1", t.preHeaderText);
                    message.AddGlobalVariable("H1", t.headline);
                    message.AddGlobalVariable("SH1", t.description);

                    if (t.templateName == "Weekly Consumption Email" || t.templateName == "Weekly Consumption Email with Editorial")
                    {
                        //get look details and fill it in
                        for (int l = 1; l <= featuredLooks.Count; l++)
                        {
                            Look look = featuredLooks[l - 1];
                            if (look.id > 0)
                            {
                                message.AddGlobalVariable("L" + l + "URL", "http://startcult.com/look.html?lookId=" + look.id + "&userName=CultCollection&url=http://startcult.com/images/100x100_identity_.png&utm_source=email&utm_medium=WeeklyDigest&utm_term=consumption");
                                message.AddGlobalVariable("L" + l + "IMG", "http://startcult.com/images/looks/" + look.id + ".jpg");
                                message.AddGlobalVariable("U" + l, look.creator.userName);
                                message.AddGlobalVariable("S" + l, (look.upVote + look.restyleCount).ToString());
                                message.AddGlobalVariable("L" + l + "DESC", look.title);
                            }
                        }

                        //get top brands
                        List <Product> hotItems   = Product.GetNewProductsByUser(userIds[i], db, 1, 6);
                        List <string>  brandNames = new List <string>();
                        for (int p = 1; p <= hotItems.Count(); p++)
                        {
                            message.AddGlobalVariable("I" + p + "IMG", hotItems[p - 1].GetNormalImageUrl());
                            message.AddGlobalVariable("I" + p, hotItems[p - 1].name);
                            message.AddGlobalVariable("B" + p, hotItems[p - 1].brandName);
                            if (!brandNames.Contains(hotItems[p - 1].brandName))
                            {
                                brandNames.Add(hotItems[p - 1].brandName);
                            }
                            message.AddGlobalVariable("R" + p, hotItems[p - 1].retailer);
                            message.AddGlobalVariable("P" + p, string.Format("{0:C}", hotItems[p - 1].price));
                            message.AddGlobalVariable("I" + p + "URL", "http://startcult.com/product.html?prodId=" + hotItems[p - 1].id + "&colorId=" + hotItems[p - 1].colors[0].canonical[0]
                                                      + "&catId=" + hotItems[p - 1].categories[0] + "&user=CultCollection&url=http://startcult.com/images/100x100_identity_.png");
                        }
                        //set header params for top 3 brands
                        message.AddGlobalVariable("EB1", brandNames[0]);
                    }
                    else if (t.templateName == "Weekly Content Email")
                    {
                        //get top looks - fill in the header param
                        //get look details and fill it in
                        for (int l = 1; l <= topLooks.Count; l++)
                        {
                            Look look = topLooks[l - 1];
                            if (look.id > 0)
                            {
                                message.AddGlobalVariable("L" + l + "URL", "http://startcult.com/look.html?lookId=" + look.id + "&userName=CultCollection&url=http://startcult.com/images/100x100_identity_.png&utm_source=email&utm_medium=WeeklyDigest&utm_term=consumption");
                                message.AddGlobalVariable("L" + l + "IMG", "http://startcult.com/images/looks/" + look.id + ".jpg");
                                message.AddGlobalVariable("U" + l, look.creator.userName);
                                message.AddGlobalVariable("S" + l, (look.upVote + look.restyleCount).ToString());
                                message.AddGlobalVariable("L" + l + "DESC", look.title);
                            }
                        }
                        // get personal top 2 looks and replace internal html

                        for (int tt = 1; tt <= featuredTags.Count; tt++)
                        {
                            Tag tag = featuredTags[tt - 1];
                            if (tag.id > 0)
                            {
                                message.AddGlobalVariable("T" + tt + "URL", "http://www.startcult.com/tag.html?tagId=" + tag.id);
                                message.AddGlobalVariable("T" + tt + "IMG", tag.imageUrl);
                                message.AddGlobalVariable("T" + tt, tag.name);
                            }
                        }
                    }

                    var result = api.SendMessage(message, t.templateName, null);
                }
            }
        }