簡體   English   中英

在 ASP.NET MVC 應用程序中從 Amazon SES 發送電子郵件

[英]Send Email From Amazon SES in ASP.NET MVC App

我在亞馬遜 ec2 上托管我的網絡應用程序,該應用程序是用 .net mvc2 編寫的。 目前使用 gmail smtp 發送電子郵件。 由於谷歌啟動電子郵件配額不能每天發送超過 500 封電子郵件。 所以決定搬家amazon ses。 如何將 amazon ses 與 asp.net mvc2 一起使用? 配置等怎么樣? 電子郵件會通過 gmail 發送嗎? 因為我們的電子郵件提供商是 gmail。 等等。

通過亞馬遜發送電子郵件是一個正確的決定。 因為當您搬到亞馬遜時,您將立即獲得每天 2000 封免費電子郵件,這比 googla 應用程序每天 500 封電子郵件配額還要多。

一步步:

  1. 轉至http://aws.amazon.com/ses ,然后單擊注冊 Amazon SES。
  2. 獲取您的 AWS 訪問標識符
  3. 驗證您的電子郵件地址 - 您將通過其發送電子郵件的電子郵件。 您需要在計算機上安裝 perl 包來測試電子郵件功能。
  4. 包括:amazonses.com 到您的 dns 記錄。

一步一步的文檔。 http://docs.aws.amazon.com/ses/latest/DeveloperGuide/getting-started.html

Codeplex 上有一個 Amazon SES(簡單電子郵件服務)C# 包裝器,您可以使用此包裝器發送電子郵件。

亞馬遜 SES C# 包裝器

最簡單的方法是通過 Nuget(包稱為 AWSSDK)下載開發工具包或從亞馬遜網站下載開發工具包。 從他們的站點下載的 sdk 有一個示例項目,向您展示如何調用他們的 API 來發送電子郵件。 唯一的配置是插入您的 api 密鑰。 最棘手的部分是驗證您的發送地址(以及任何測試接收者),但它們也是發送測試消息的 API 調用。 然后,您需要登錄並驗證這些電子郵件地址。 電子郵件將通過亞馬遜發送(這就是重點),但發件人電子郵件地址可以是您的 gmail 地址。

@gandil 我創建了這個非常簡單的代碼來發送電子郵件

using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using System.IO;

namespace SendEmail
{
 class Program
 {
    static void Main(string[] args)
    {
        //Remember to enter your (AWSAccessKeyID, AWSSecretAccessKey) if not using and IAM User with credentials assigned to your instance and your RegionEndpoint
        using (var client = new AmazonSimpleEmailServiceClient("YourAWSAccessKeyID", "YourAWSSecretAccessKey", RegionEndpoint.USEast1))
        {
            var emailRequest =  new SendEmailRequest()
            {
                Source = "FROMADDRESS@TEST.COM",
                Destination = new Destination(),
                Message = new Message()
            };

            emailRequest.Destination.ToAddresses.Add("TOADDRESS@TEST.COM");
            emailRequest.Message.Subject = new Content("Hello World");
            emailRequest.Message.Body = new Body(new Content("Hello World"));
            client.SendEmail(emailRequest);
        }
     }
  }
}

你可以在這里找到代碼https://github.com/gianluis90/amazon-send-email

  1. 使用以下命名空間從互聯網下載 AWSSDK.dll 文件
using Amazon; using Amazon.SimpleEmail; using Amazon.SimpleEmail.Model; using System.Net.Mail;

2 . 添加到網絡配置...

 <appSettings>
     <add key="AWSAccessKey" value="Your AWS Access Key" />
     <add key="AWSSecretKey" value="Your AWS secret Key" />
 </appSettings>

3 . 將 AWSEmailSevice 類添加到您的項目中,該類將允許通過 AWS 服務發送郵件...

public class AWSEmailSevice
    {

        //create smtp client instance...
        SmtpClient smtpClient = new SmtpClient();

        //for sent mail notification...
        bool _isMailSent = false;

        //Attached file path...
        public string AttachedFile = string.Empty;

        //HTML Template used in mail ...
        public string Template = string.Empty;

        //hold the final template data list of users...
        public string _finalTemplate = string.Empty;

        //Template replacements varibales dictionary....
        public Dictionary<string, string> Replacements = new Dictionary<string, string>();


        public bool SendMail(MailMessage mailMessage)
        {
            try
            {

                if (mailMessage != null)
                {
                    //code for fixed things
                    //from address...
                    mailMessage.From = new MailAddress("from@gmail.com");

                    //set priority high
                    mailMessage.Priority = System.Net.Mail.MailPriority.High;

                    //Allow html true..
                    mailMessage.IsBodyHtml = true;

                    //Set attachment data..
                    if (!string.IsNullOrEmpty(AttachedFile))
                    {
                        //clear old attachment..
                        mailMessage.Attachments.Clear();

                        Attachment atchFile = new Attachment(AttachedFile);
                        mailMessage.Attachments.Add(atchFile);
                    }

                    //Read email template data ...
                    if (!string.IsNullOrEmpty(Template))
                        _finalTemplate = File.ReadAllText(Template);

                    //check replacements ...
                    if (Replacements.Count > 0)
                    {
                        //exception attached template..
                        if (string.IsNullOrEmpty(_finalTemplate))
                        {
                            throw new Exception("Set Template field (i.e. file path) while using replacement field");
                        }

                        foreach (var item in Replacements)
                        {
                            //Replace Required Variables...
                            _finalTemplate = _finalTemplate.Replace("<%" + item.Key.ToString() + "%>", item.Value.ToString());
                        }
                    }

                    //Set template...
                    mailMessage.Body = _finalTemplate;


                    //Send Email Using AWS SES...
                    var message = mailMessage;
                    var stream = FromMailMessageToMemoryStream(message);
                    using (AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(
                               ConfigurationManager.AppSettings["AWSAccessKey"].ToString(),
                               ConfigurationManager.AppSettings["AWSSecretKey"].ToString(), 
                               RegionEndpoint.USWest2))
                    {
                        var sendRequest = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
                        var response = client.SendRawEmail(sendRequest);

                        //return true ...
                    _isMailSent = true;

                    }
                }
                else
                {
                    _isMailSent = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return _isMailSent;
        }

        private MemoryStream FromMailMessageToMemoryStream(MailMessage message)
        {
            Assembly assembly = typeof(SmtpClient).Assembly;

            Type mailWriterType = assembly.GetType("System.Net.Mail.MailWriter");

            MemoryStream stream = new MemoryStream();

            ConstructorInfo mailWriterContructor =
               mailWriterType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(Stream) }, null);
            object mailWriter = mailWriterContructor.Invoke(new object[] { stream });

            MethodInfo sendMethod =
               typeof(MailMessage).GetMethod("Send", BindingFlags.Instance | BindingFlags.NonPublic);

            if (sendMethod.GetParameters().Length == 3)
            {
                sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true, true }, null); // .NET 4.x
            }
            else
            {
                sendMethod.Invoke(message, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { mailWriter, true }, null); // .NET < 4.0 
            }

            MethodInfo closeMethod =
               mailWriter.GetType().GetMethod("Close", BindingFlags.Instance | BindingFlags.NonPublic);
            closeMethod.Invoke(mailWriter, BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { }, null);

            return stream;
        }
    }
  1. 使用上面的類向任何人發送帶有附件和模板變量替換的郵件(它是可選的) // 調用此方法發送您的電子郵件

public string SendEmailViaAWS() { string emailStatus = "";

 //Create instance for send email... AWSEmailSevice emailContaint = new AWSEmailSevice(); MailMessage emailStuff = new MailMessage(); //email subject.. emailStuff.Subject = "Your Email subject"; //region Optional email stuff //Templates to be used in email / Add your Html template path .. emailContaint.Template = @"\\Templates\\MyUserNotification.html"; //add file attachment / add your file ... emailContaint.AttachedFile = "\\ExcelReport\\report.pdf"; //Note :In case of template //if youe want to replace variables in run time //just add replacements like <%FirstName%> , <%OrderNo%> , in HTML Template //if you are using some varibales in template then add // Hold first name.. var FirstName = "User First Name"; // Hold email.. var OrderNo = 1236; //firstname replacement.. emailContaint.Replacements.Add("FirstName", FirstName.ToString()); emailContaint.Replacements.Add("OrderNo", OrderNo.ToString()); // endregion option email stuff //user OrderNo replacement... emailContaint.To.Add(new MailAddress("TOEmail@gmail.com")); //mail sent status bool isSent = emailContaint.SendMail(emailStuff); if(isSent) { emailStatus = "Success"; } else { emailStatus = "Fail"; } return emailStatus ; }

以下是我如何發送帶附件的電子郵件

  public static void SendMailSynch(string file1, string sentFrom, List<string> recipientsList, string subject, string body)
    {

        string smtpClient = "email-smtp.us-east-1.amazonaws.com"; //Correct it
        string conSMTPUsername = "<USERNAME>";
        string conSMTPPassword = "<PWD>";

        string username = conSMTPUsername;
        string password = conSMTPPassword;

        // Configure the client:
        System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpClient);
        client.Port = 25;
        client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;

        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(username, password);
        client.EnableSsl = true;
        client.Credentials = credentials;

        // Create the message:
        var mail = new System.Net.Mail.MailMessage();
        mail.From = new MailAddress(sentFrom);
        foreach (string recipient in recipientsList)
        {
            mail.To.Add(recipient);
        }
        mail.Bcc.Add("test@test.com");
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;


        Attachment attachment1 = new Attachment(file1, MediaTypeNames.Application.Octet);


        ContentDisposition disposition = attachment1.ContentDisposition;
        disposition.CreationDate = System.IO.File.GetCreationTime(file1);
        disposition.ModificationDate = System.IO.File.GetLastWriteTime(file1);
        disposition.ReadDate = System.IO.File.GetLastAccessTime(file1);

        mail.Attachments.Add(attachment1);

        client.Send(mail);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM