在 ASP.NET MVC 应用程序中从 Amazon SES 发送电子邮件

发布于 2024-11-15 16:26:38 字数 202 浏览 2 评论 0原文

我在 amazon ec2 上托管用 .net mvc2 编写的 Web 应用程序。目前使用 gmail smtp 发送电子邮件。由于谷歌的启动电子邮件配额无法每天发送超过 500 封电子邮件。所以决定迁移亚马逊ses。如何将 amazon ses 与 asp.net mvc2 一起使用?配置等怎么样?电子邮件将通过 Gmail 发送吗?因为我们的电子邮件提供商是 gmail。 ETC。

I host my web app which is written in .net mvc2 on amazon ec2. currrently use gmail smtp to send email. beacuse of google for startup email quota cant send more than 500 email a day. So decide to move amazon ses. How can use amazon ses with asp.net mvc2? How about configuration etc? Is email will send via gmail? because our email provider is gmail. etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

瞄了个咪的 2024-11-22 16:26:38

通过亚马逊发送电子邮件是一个正确的决定。因为当您转移到亚马逊时,您将立即获得每天 2000 封免费电子邮件,这比 googla apps 每天 500 封电子邮件的配额还要多。

逐步操作:

  1. 转到 http://aws.amazon.com/ses
    并单击注册 Amazon SES。
  2. 要获取您的 AWS 访问标识符,
  3. 请验证您的电子邮件地址 - email
    您将通过它发送电子邮件。你
    需要安装 perl 软件包
    您的计算机用于测试电子邮件
    特征。
  4. 将:amazonses.com 添加到您的 DNS 记录中。

逐步文档。
http://docs.aws.amazon.com/ses/latest /DeveloperGuide/getting-started.html

Codeplex 上有一个 Amazon SES(简单电子邮件服务)C# 包装器,您可以使用此包装器发送电子邮件。

Amazon SES C# 包装器

Send Email via Amazon is a right decision. Because when you move to amazon you will immediately get 2000 email free per day which is greater than googla apps 500 emails quota a day.

Step by Step:

  1. Go to http://aws.amazon.com/ses
    and click Sign Up for Amazon SES.
  2. To get your AWS access identifiers
  3. verify your email address - email
    which you will send email via. You
    need perl packages installled on
    your computer to test email
    features.
  4. include:amazonses.com to your dns record.

Step by step documentation.
http://docs.aws.amazon.com/ses/latest/DeveloperGuide/getting-started.html

There is a Amazon SES (Simple Email Service) C# Wrapper on codeplex you can use this wrapper to send emails.

Amazon SES C# Wrapper

丘比特射中我 2024-11-22 16:26:38

最简单的方法是通过 Nuget 下载 SDK(软件包称为 AWSSDK)或从 Amazon 网站下载 SDK。从他们的网站下载的 sdk 有一个示例项目,向您展示如何调用他们的 API 来发送电子邮件。唯一的配置是插入您的 api 密钥。最棘手的部分是验证您的发送地址(以及任何测试收件人),但它们也是一个 API 调用来发送测试消息。然后,您需要登录并验证这些电子邮件地址。电子邮件将通过亚马逊发送(这就是重点),但发件人电子邮件地址可以是您的 Gmail 地址。

Easiest way is to download the SDK via Nuget (package is called AWSSDK) or download the SDK from Amazon's site. The sdk download from their site has an example project that shows you how to call their API to send email. The only configuration is plugging in your api keys. The trickiest part is verifying your send address (and any test receipients) but their is an API call there too to send the test message. You will then need to log in and verify those email addresses. The email will be sent through Amazon (that is the whole point) but the from email address can be your gmail address.

不喜欢何必死缠烂打 2024-11-22 16:26:38

@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 = "[email protected]",
                Destination = new Destination(),
                Message = new Message()
            };

            emailRequest.Destination.ToAddresses.Add("[email protected]");
            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

@gandil I created this very simple code to send emails

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 = "[email protected]",
                Destination = new Destination(),
                Message = new Message()
            };

            emailRequest.Destination.ToAddresses.Add("[email protected]");
            emailRequest.Message.Subject = new Content("Hello World");
            emailRequest.Message.Body = new Body(new Content("Hello World"));
            client.SendEmail(emailRequest);
        }
     }
  }
}

You can find the code in here https://github.com/gianluis90/amazon-send-email

锦欢 2024-11-22 16:26:38

以下是我发送带有附件的电子邮件的方式

  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("[email protected]");
        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);
    }

Following is how I sent email with attachment

  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("[email protected]");
        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);
    }
雪花飘飘的天空 2024-11-22 16:26:38
  1. 从互联网下载 AWSSDK.dll 文件
    使用以下命名空间
使用亚马逊;
使用 Amazon.SimpleEmail;
使用 Amazon.SimpleEmail.Model;

使用 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 ses 发送邮件...

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("[email protected]");

                    //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. 使用上面的类向任何具有附件和模板变量替换的人发送邮件(可选)
    // 调用此方法发送您的电子邮件

公共字符串SendEmailViaAWS()
{
字符串 emailStatus = "";

 //创建发送电子邮件的实例...
      AWSEmailSevice emailContaint = new AWSEmailSevice();
      MailMessage emailStuff = new MailMessage();

       //电子邮件主题..
      emailStuff.Subject = "您的电子邮件主题";

        //region 可选的电子邮件内容

      //要在电子邮件中使用的模板/添加您的 Html 模板路径..
      emailContaint.Template = @"\Templates\MyUserNotification.html";

      //添加文件附件/添加您的文件...
      emailContaint.AttachedFile = "\ExcelReport\report.pdf";



        //注意:如果是模板 
        //如果你想在运行时替换变量 
        //只需添加替换,如<%FirstName%> , <%订单号%> , 在 HTML 模板中 


        //如果您在模板中使用一些变量,则添加 
      // 保留名字..
      var FirstName = "用户名字";

      // 保留电子邮件..
      var 订单号 = 1236;


      //名字替换..
      emailContaint.Replacements.Add("FirstName", FirstName.ToString());
      emailContaint.Replacements.Add("OrderNo", OrderNo.ToString());

        // endregion 选项电子邮件内容


      //用户订单无换货...
      emailContaint.To.Add(new MailAddress("[电子邮件受保护]") );

      //邮件发送状态
      bool isSent = emailContaint.SendMail(emailStuff);

      if(已发送)
      {
         emailStatus = "成功";
      }
      别的
      {
      emailStatus = "失败";
      }
         返回电子邮件状态; }
  1. Download AWSSDK.dll file from internet
    use following name-spaces
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;

using System.Net.Mail;

2 . Add to web config...

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

3 . Add a AWSEmailSevice class to your project that will allow to send mail via AWS ses...

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("[email protected]");

                    //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. Use above class to send mail anyone with attachment and template varibales replacement (it's optional)
    // Call this method to send your email

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("[email protected]"));

      //mail sent status
      bool isSent = emailContaint.SendMail(emailStuff);

      if(isSent)
      {
         emailStatus = "Success";
      }
      else
      {
      emailStatus = "Fail";
      }
         return emailStatus ;    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文