如何使用Amazone SES向订阅者发送同步邮件

时间:2017-01-25 19:21:07

标签: c# amazon-web-services amazon-s3 linq-to-sql asp.net-4.0

我正在使用一个大型邮件发送程序,该程序现在可以向用户发送数十封与go-daddy的邮件,我想在我的项目中使用amazone ses。我如何检索密钥以及如何逐步实施此服务请帮助我。

这是我的网络应用程序LINQTOSQL图表:

LINQTOSQL OR MAPPING

现在我只想实施此方法向所有属于特定类别的嫌疑人发送电子邮件。例如:

enter image description here

这里当选择Categroy时,我必须向几十个特定类别的嫌疑人发送一封电子邮件,如:

enter image description here

以下是我向所有订阅者发送邮件的代码:

     protected void submit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                System.Threading.Thread.Sleep(2000);
                List<string> file_names = new List<string>();
                string ToUser = txt_ComName2.Text.Trim();
                char touser1 = Convert.ToChar(ToUser.Substring(ToUser.Length - 1, 1));
                string Cc = null;
                if (!string.IsNullOrEmpty(txt_ComName3.Text.Trim()))
                {
                    Cc = txt_ComName3.Text.Trim();
                }
                string Bcc = null;
                if (!string.IsNullOrEmpty(txt_ComName4.Text.Trim()))
                {
                    Bcc = txt_ComName4.Text.Trim();
                }
                char? cc1 = null;
                if (!string.IsNullOrEmpty(Cc))
                {
                    cc1 = Convert.ToChar(Cc.Substring(Cc.Length - 1, 1));
                }
                char? bcc1 = null;
                if (!string.IsNullOrEmpty(Bcc))
                {
                    bcc1 = Convert.ToChar(Bcc.Substring(Bcc.Length - 1, 1));
                }
                bool FileAttached;
                if (file_upload.FileContent.Length > 0)
                {
                    FileAttached = true;
                }
                else
                {
                    FileAttached = false;
                }
                using (DataClassesDataContext db = new DataClassesDataContext())
                {
                    int userid = db.Users.Where(u => u.EmailAddress.Equals((String)Session["EmailID"])).Select(u => u.Id).FirstOrDefault();
.....
                                Util.SendReplyMailAll(int.Parse(email_id.Value.ToString()), userid, txt_ComName.Text.Trim(), (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, sbody, file_names.ToList());
                            }
                        }
                        else
                        {
                            var searchfromuser = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName1.Text.Trim()) && f.user_id.Equals(userid)).Select(f => f).SingleOrDefault();
                            if (searchfromuser != null)
                            {
                                int fromuserid = int.Parse(searchfromuser.Id.ToString());
                                Email myEmail = new Email();
                                ......
                                db.UpdateEmailField(newId, "TotalFileSize", tot_file_size.ToString());
                                string sbody = ConvertAllString(CKEditor1.Text.Trim());
                                Util.SendReplyMail(newId, txt_ComName.Text.Trim(), Host, Port, EnableSSl, Email, Password, (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser, (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, sbody, file_names.ToList());
                                var loggedMessage = db.LoggedMessages.Where(l => l.email_id.Equals(newId)).Select(l => l).ToList();
                                foreach (var message in loggedMessage)
                                {
                                    if (message.Sent == true)
                                    {
                                        ltr_message.Text = "Mail Sent Successfully.";
                                    }
                                    else if (message.Sent == false)
                                    {
                                        ltr_message.Text = message.SmtpException.ToString() + "&nbsp;&nbsp;" + message.InnerExceptionDetails.ToString();
                                    }
                                }
                                UpdatePanel28.Update();
                            }
                            else
                            {
                                ltr_message.Text = "From User doesn't exist in record.";
                            }
                        }
                    }
                    else if ((String)Session["new_flag"] == "False")
                    {
                        if (chkAll.Checked)
                        {
                            if (db.FromUsers.Where(f => f.user_id.Equals(userid)).Count() > 0)
                            {
                                var searchfusers = db.FromUsers.Where(f => f.user_id.Equals(userid)).Select(f => f).FirstOrDefault();
                                if (searchfusers != null)
                                {
                                    db.UpdateEmail(int.Parse(email_id.Value.ToString()), txt_ComName.Text.Trim(), null, null, (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, CKEditor1.Text.Trim(), FileAttached, DateTime.Parse(System.DateTime.Now.ToString()));
                                    db.SubmitChanges();
                                    HttpFileCollection fileCollection = Request.Files;
                                    double tot_file_size = 0;
                                    for (int i = 0; i < fileCollection.Count; i++)
                                    {
                                        File myFile = new File();
                                        HttpPostedFile uploadfile = fileCollection[i];
                                        string fileTitle = Path.GetFileName(uploadfile.FileName);
                                        string fileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
                                        string fileType = System.IO.Path.GetExtension(fileTitle).ToString().ToLower();
                                        myFile.Email_Id = int.Parse(email_id.Value.ToString());
                                        myFile.File_Title = fileTitle;
                                        myFile.File_name = fileName;
                                        myFile.File_ext = fileType;
                                        double file_size = int.Parse(uploadfile.ContentLength.ToString()) / 1024;
                                        tot_file_size += file_size;
                                        myFile.File_Size = file_size;
                                        if (uploadfile.ContentLength > 0)
                                        {
                                            uploadfile.SaveAs(Server.MapPath("~/EmailFiles/") + fileName + fileType);
                                            db.Files.InsertOnSubmit(myFile);
                                            db.SubmitChanges();
                                            file_names.Add(fileName + fileType);
                                        }
                                    }
                                    db.UpdateEmailField(int.Parse(email_id.Value.ToString()), "TotalFileSize", tot_file_size.ToString());
                                    string sbody = ConvertAllString(CKEditor1.Text.Trim());
                                    Util.SendReplyMailAll(int.Parse(email_id.Value.ToString()), userid, txt_ComName.Text.Trim(), (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, sbody, file_names.ToList());
                                }
                            }
                        }
                        else
                        {
                            var searchfromuser = db.FromUsers.Where(f => f.EmailAddress.Equals(txt_ComName1.Text.Trim()) && f.user_id.Equals(userid)).Select(f => f).SingleOrDefault();
                            if (searchfromuser != null)
                            {
                                int fromuserid = int.Parse(searchfromuser.Id.ToString());
                                db.UpdateEmail(int.Parse(email_id.Value.ToString()), txt_ComName.Text.Trim(), fromuserid, (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser, (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, CKEditor1.Text.Trim(), FileAttached, DateTime.Parse(System.DateTime.Now.ToString()));
                                db.SubmitChanges();
                                HttpFileCollection fileCollection = Request.Files;
                                double tot_file_size = 0;
                                for (int i = 0; i < fileCollection.Count; i++)
                                {
                                    File myFile = new File();
                                    HttpPostedFile uploadfile = fileCollection[i];
                                    string fileTitle = Path.GetFileName(uploadfile.FileName);
                                    string fileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
                                    string fileType = System.IO.Path.GetExtension(fileTitle).ToString().ToLower();
                                    myFile.Email_Id = int.Parse(email_id.Value.ToString());
                                    myFile.File_Title = fileTitle;
                                    myFile.File_name = fileName;
                                    myFile.File_ext = fileType;
                                    double file_size = int.Parse(uploadfile.ContentLength.ToString()) / 1024;
                                    tot_file_size += file_size;
                                    myFile.File_Size = file_size;
                                    if (uploadfile.ContentLength > 0)
                                    {
                                        uploadfile.SaveAs(Server.MapPath("~/EmailFiles/") + fileName + fileType);
                                        db.Files.InsertOnSubmit(myFile);
                                        db.SubmitChanges();
                                        file_names.Add(fileName + fileType);
                                    }
                                }
                                var fileNames = db.Files.Where(f => f.Email_Id.Equals(int.Parse(email_id.Value.ToString()))).Select(f => f).ToList();
                                if (fileNames.Count > 0)
                                {
                                    foreach (var item in fileNames)
                                    {
                                        file_names.Add(item.File_name.ToString() + item.File_ext.ToString());
                                    }
                                }
                                db.UpdateEmailField(int.Parse(email_id.Value.ToString()), "TotalFileSize", tot_file_size.ToString());
                                string sbody = ConvertAllString(CKEditor1.Text.Trim());
                                Util.SendReplyMail(int.Parse(email_id.Value.ToString()), txt_ComName.Text.Trim(), Host, Port, EnableSSl, Email, Password, (touser1 == ',') ? ToUser.TrimEnd(',') : ToUser, (cc1 == ',') ? Cc.TrimEnd(',') : Cc, (bcc1 == ',') ? Bcc.TrimEnd(',') : Bcc, sbody, file_names.ToList());
                                var loggedMessage = db.LoggedMessages.Where(l => l.email_id.Equals(int.Parse(email_id.Value.ToString()))).Select(l => l).ToList();
                                foreach (var message in loggedMessage)
                                {
                                    if (message.Sent == true)
                                    {
                                        ltr_message.Text = "Mail Sent Successfully.";
                                    }
                                    else if (message.Sent == false)
                                    {
                                        ltr_message.Text = message.SmtpException.ToString() + "&nbsp;&nbsp;" + message.InnerExceptionDetails.ToString();
                                    }
                                }
                                UpdatePanel28.Update();
                            }
                        }
                    }
                    Panel_AddNew.Visible = false;
                    Panel_ViewPostList.Visible = true;
                    this.FillGrid((String)Session["StartAlpha"] ?? null, (String)Session["CommandName"] ?? null, (String)Session["ColumnName"] ?? null, (String)Session["SearchText"] ?? null);
                }
            }
        }

这是我的两个功能一个用于Send Fixed Suscribers邮件,另一个是同时邮件给所有具有特定类别的用户...

    public static void SendReplyMail(int emailId,string subject, string Host, string Port, bool enableSSL,string email, string password, string emails, string ccs, string bccs, string body, List<string> file_names)
    {
        MailMessage msg = new MailMessage();
        System.Net.Mail.SmtpClient client = Util.GetSmtpClient();
        msg.IsBodyHtml = true;
        client.Host = Host;
        System.Net.NetworkCredential basicauthenticationinfo = new System.Net.NetworkCredential(email, password);
        client.Port = int.Parse(Port);
        client.EnableSsl = enableSSL;
        client.UseDefaultCredentials = false;
        client.Credentials = basicauthenticationinfo;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        msg.From = new MailAddress(email);
        msg.Priority = MailPriority.High;
        ..
                    msg.Attachments.Add(mailAttachment);
                }
            }
        }
        try
        {
            client.Send(msg);
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                LoggedMessage myMessage = new LoggedMessage();
                myMessage.email_id = emailId;
                myMessage.Sent = true;
                db.LoggedMessages.InsertOnSubmit(myMessage);
                db.SubmitChanges();
            }
        }
        catch (SmtpException ex)
        {
            using (DataClassesDataContext db = new DataClassesDataContext())
            {
                LoggedMessage myMessage = new LoggedMessage();
                myMessage.email_id = emailId;
                myMessage.Sent = false;
                myMessage.SmtpException = ex.Message.ToString();
                if (ex.InnerException.Message != null)
                {
                    myMessage.InnerExceptionDetails = ex.InnerException.Message.ToString();
                }
                db.LoggedMessages.InsertOnSubmit(myMessage);
                db.SubmitChanges();
            }
        }
    }

    public static void SendReplyMailAll(int emailId,int userid,string subject, string ccs, string bccs, string body, List<string> file_names)
    {
        using (DataClassesDataContext db = new DataClassesDataContext())
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("Id", typeof(int)));
            dt.Columns.Add(new DataColumn("Host", typeof(string)));
            dt.Columns.Add(new DataColumn("Port", typeof(string)));
            dt.Columns.Add(new DataColumn("EmailAddress", typeof(string)));
            dt.Columns.Add(new DataColumn("Password", typeof(string)));
            dt.Columns.Add(new DataColumn("EnableSSL", typeof(bool)));
            DataTable dt1 = new DataTable();
            dt1.Columns.Add(new DataColumn("Id", typeof(int)));
            dt1.Columns.Add(new DataColumn("Email", typeof(string)));
            if (db.FromUsers.Where(f=>f.user_id.Equals(userid)).Count() > 0 && db.Subscribers.Where(s=>s.user_id.Equals(userid)).Count() > 0)
            {
                SmtpClient client = new SmtpClient();
                if (db.Subscribers.Where(s=>s.user_id.Equals(userid)).Count() > 99)
                {
                    for (int i = 0; i < db.FromUsers.Where(f=>f.user_id.Equals(userid)).Count(); i++)
                    {
                        foreach (var item in db.FromUsers.OrderBy(f => f.Id).Where(f => f.user_id.Equals(userid) && SqlMethods.DateDiffMinute(f.SentDateTime.Value.Date, DateTime.Now.Date) > 60).Select(f => new
                        {
                            Id = f.Id,
                            Host = f.Host,
                            Port = f.Port,
                            SenderEmail = f.EmailAddress,
                            SenderPassword = f.Password,
                            EnableSSL = f.EnableSSL
                        }).ToList())
                        {
                            if (item != null)
                            {
                                DataRow dr = dt.NewRow();
                                dr["Id"] = int.Parse(item.Id.ToString());
                                dr["Host"] = item.Host.ToString();
                                dr["Port"] = item.Port.ToString();
                                dr["EmailAddress"] = item.SenderEmail.ToString();
                                dr["Password"] = item.SenderPassword.ToString();
                                dr["EnableSSL"] = item.EnableSSL;
                                dt.Rows.Add(dr);
                            }
                        }
                        client.Host = dt.Rows[i]["Host"].ToString();
                        System.Net.NetworkCredential basicauthenticationinfo = new System.Net.NetworkCredential(dt.Rows[i]["EmailAddress"].ToString(), dt.Rows[i]["Password"].ToString());
                        client.Port = int.Parse(dt.Rows[i]["Port"].ToString());
                        client.EnableSsl = bool.Parse(dt.Rows[i]["EnableSSL"].ToString());
                        client.UseDefaultCredentials = false;
                        client.Credentials = basicauthenticationinfo;
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        MailMessage msg = new MailMessage();
                        msg.IsBodyHtml = true;
                        msg.Priority = MailPriority.High;
                        msg.From = new MailAddress(dt.Rows[i]["EmailAddress"].ToString());
                        var subscriber = Enumerable.Repeat(new
                        {
                            Id = default(int),
                            Email = string.Empty
                        }, 0).ToList();
                        if (db.Setups.Count() > 0)
                        {
                            int id = int.Parse(db.Setups.Select(s => s.SUB_ID).ToString());
                            subscriber = db.Subscribers.Where(s=>s.user_id.Equals(userid)).ToList().OrderBy(s => s.Id).Where(s => s.Id > id && s.SentMail.Equals(0)).Select(s => new { Id = s.Id, Email = s.EmailAddress }).ToList();
                        }
                        else
                        {
                            subscriber = db.Subscribers.Where(s=>s.user_id.Equals(userid)).ToList().OrderBy(s => s.Id).Where(s => s.SentMail.Equals(0)).Select(s => new { Id = s.Id, Email = s.EmailAddress }).ToList();
                        }
                        foreach (var item in subscriber)
                        {
                            DataRow dr = dt1.NewRow();
                            dr["Id"] = int.Parse(item.Id.ToString());
                            dr["Email"] = item.Email.ToString();
                            dt1.Rows.Add(dr);
                        }
                        string emails = null;
                        for (int j = 0; j <= 99; j++)
                        {
                            emails += "," + dt1.Rows[j][1].ToString();
                        }
                        int LastId = int.Parse(db.Subscribers.Where(s=>s.user_id.Equals(userid)).OrderByDescending(s => s.Id).Select(s => s.Id).Take(99).First().ToString());
                        db.ExecuteCommand("UPDATE [dbo].[tbl_Setup] SET [SUB_ID] = {0}", LastId);
                        emails = emails.Substring(1, emails.Length - 1).ToString();
                        if (emails.Contains(","))
                        {
                            string[] values1 = emails.Split(',');
                            for (int k = 0; k < values1.Length; k++)
                            {
                                values1[k] = values1[k].Trim();
                            }
                            foreach (var item1 in values1)
                            {
                                msg.To.Add(new MailAddress(item1.ToString()));
                                db.ExecuteCommand("UPDATE [dbo].[tbl_Subscribers] SET [SentMail] = 2 WHERE user_id ={0} && EmailAddress = {1}",userid,emails);
                            }
                        }
                        else
                        {
                            msg.To.Add(new MailAddress(emails));
                            db.ExecuteCommand("UPDATE [dbo].[tbl_Subscribers] SET [SentMail] = 2 WHERE user_id ={0} && EmailAddress = {1}",userid,emails);
                        }
                        if (!string.IsNullOrEmpty(ccs))
                        {
                            if (ccs.Contains(","))
                            {
                                string[] values2 = ccs.Split(',');
                                for (int l = 0; l < values2.Length; l++)
                                {
                                    values2[l] = values2[l].Trim();
                                }
                                foreach (var item2 in values2)
                                {
                                    msg.CC.Add(new MailAddress(item2.ToString()));
                                }
                            }
                            else
                            {
                                msg.CC.Add(new MailAddress(ccs));
                            }
                        }
                        if (!string.IsNullOrEmpty(bccs))
                        {
                            if (bccs.Contains(","))
                            {
                                string[] values3 = bccs.Split(',');
                                for (int m = 0; m < values3.Length; m++)
                                {
                                    values3[m] = values3[m].Trim();
                                }
                                foreach (var item3 in values3)
                                {
                                    msg.Bcc.Add(new MailAddress(item3.ToString()));
                                }
                            }
                            else
                            {
                                msg.Bcc.Add(new MailAddress(bccs));
                            }
                        }
                        msg.Subject = subject;
                        msg.Body = body;
                        string fbody = body.Replace("\"", "'");
                        ..
                }
            }
        }
    }

第一种方法如何工作正常,但我如何使用Amazone SES实现第二种方法,以便向所有订阅者发送同步邮件。

请帮帮我......

0 个答案:

没有答案