質問

Amazon EC2で.NET MVC2で記述されているWebアプリをホストしています。 Gmail SMTPを使用して電子メールを送信します。 GoogleのBeacuse for Startupメールクォータは、1日に500メール以上を送信できます。したがって、Amazon SESを移動することにしました。 ASP.NET MVC2でAmazon SESを使用するにはどうすればよいですか?構成などはどうですか?メールはGmailで送信されますか?メールプロバイダーはGmailだからです。等

役に立ちましたか?

解決

Amazon経由で電子メールを送信することは正しい決定です。 Amazonに移動すると、1日あたり2000メールが1日に無料で無料で入手できます。

ステップバイステップ:

  1. 行きます http://aws.amazon.com/sesAmazon SESのサインアップをクリックします。
  2. AWSアクセス識別子を取得するには
  3. メールアドレスを確認します - メールで送信するメール。電子メール機能をテストするには、コンピューターにインストールされているPerlパッケージが必要です。
  4. 含める:amazonses.comへのDNSレコード。

ステップバイステップのドキュメント。http://docs.aws.amazon.com/ses/latest/developerguide/getting-started.html

Amazon SES(Simple Email Service)c#wrapper codeplexには、このラッパーを使用してメールを送信できます。

Amazon SES C#ラッパー

他のヒント

最も簡単な方法は、NUGET(パッケージはAWSSDKと呼ばれる)を介してSDKをダウンロードするか、AmazonのサイトからSDKをダウンロードすることです。彼らのサイトからのSDKのダウンロードには、電子メールを送信するためにAPIを呼び出す方法を示すプロジェクトの例があります。唯一の構成は、APIキーに接続することです。最もトリッキーな部分は、送信アドレス(およびテスト受信者)を確認することですが、テストメッセージを送信するためにAPI呼び出しもあります。その後、これらのメールアドレスをログインして確認する必要があります。電子メールはAmazonから送信されます(これは全体のポイントです)が、メールアドレスからGmailアドレスになることができます。

  1. 次の名前の次のインターネット使用からawssdk.dllファイルをダウンロードします
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;

using System.Net.Mail;

2。 Web構成に追加...

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

3。 AWS SESを介してメールを送信できるAwsemailseviceクラスをプロジェクトに追加してください...

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 ;    }

@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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top