Container for the parameters to the SendRawEmail operation.

Sends an email message, with header and content specified by the client. The SendRawEmail action is useful for sending multipart MIME emails, with attachments or inline content.

The raw text of the message must comply with Internet email standards; otherwise, the message cannot be sent. For more information, go to the Amazon SES Developer Guide.

상속: Amazon.Runtime.AmazonWebServiceRequest
예제 #1
0
    public static void SESSendRawEmail()
    {
      #region SESSendRawEmail
      // using System.IO;

      var sesClient = new AmazonSimpleEmailServiceClient();

      var stream = new MemoryStream(
        Encoding.UTF8.GetBytes("From: [email protected]\n" +
          "To: [email protected]\n" +
          "Subject: You're invited to the meeting\n" +
          "Content-Type: text/plain\n\n" +
          "Please join us Monday at 7:00 PM.")
      );

      var raw = new RawMessage
      {
        Data = stream
      };

      var to = new List<string>() { "*****@*****.**" };
      var from = "*****@*****.**";

      var request = new SendRawEmailRequest
      {
        Destinations = to,
        RawMessage = raw,
        Source = from
      };

      sesClient.SendRawEmail(request);
      #endregion
    }
예제 #2
0
    public static string sendInvEmail(string email, string subject, string msg, string attach1, string attach2)
    {
        try
        {
            Amazon.SimpleEmail.AmazonSimpleEmailServiceConfig config = new Amazon.SimpleEmail.AmazonSimpleEmailServiceConfig();
            config.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
            Amazon.SimpleEmail.AmazonSimpleEmailServiceClient client = new Amazon.SimpleEmail.AmazonSimpleEmailServiceClient("AKIAI6NU4VLLI32AI2UA", Cryptography.Decrypt("NdL0xWLhvbF6pvu3hw1FtluhPmUc1jAuWKgj6mb4V89KztEq6MjEhQoiCPLVv4y9"), config);
            var         stream     = new MemoryStream();
            MimeMessage objMessage = new MimeMessage();
            string[]    emls       = email.Split(',');
            foreach (string eml in emls)
            {
                objMessage.To.Add(new MailboxAddress(string.Empty, eml));
            }
            objMessage.From.Add(new MailboxAddress("InfnIT Invoice", "*****@*****.**"));
            objMessage.Subject = subject;
            BodyBuilder emailBodyObj = new BodyBuilder();
            emailBodyObj.HtmlBody = msg;
            emailBodyObj.Attachments.Add(attach1);
            emailBodyObj.Attachments.Add(attach2);
            objMessage.Body = emailBodyObj.ToMessageBody();
            objMessage.WriteTo(stream);
            Amazon.SimpleEmail.Model.SendRawEmailRequest mailObj = new Amazon.SimpleEmail.Model.SendRawEmailRequest(new RawMessage(stream));
            SendRawEmailResponse response = client.SendRawEmail(mailObj);
            string res = response.MessageId;

            System.Net.Mail.MailMessage aMessage = new System.Net.Mail.MailMessage();
            aMessage.From = new System.Net.Mail.MailAddress("*****@*****.**", "InfnIT Invoice");

            //aMessage.To.Add(email);
            //aMessage.ReplyTo = new System.Net.Mail.MailAddress("*****@*****.**");
            //aMessage.Subject = subject;
            //System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(msg, System.Text.Encoding.UTF8, "text/html");
            //aMessage.IsBodyHtml = true;
            //aMessage.BodyEncoding = System.Text.Encoding.UTF8;
            //aMessage.Attachments.Add(new System.Net.Mail.Attachment(attach1));
            //aMessage.Attachments.Add(new System.Net.Mail.Attachment(attach2));

            //aMessage.AlternateViews.Add(htmlView);
            //System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient();
            //mailClient.Host = "smtp.gmail.com";
            //mailClient.Port = 587;
            //mailClient.EnableSsl = true;
            //mailClient.Credentials = new System.Net.NetworkCredential("*****@*****.**", "m4iling2");

            //mailClient.Send(aMessage);

            return("success");//downloadCfdi += "<p>Correo enviado";
        }
        catch (Exception ex)
        {
            return(ex.Message);
            //downloadCfdi += "<p><i class=\"w3-red\">No se pudo enviar el correo: +" + ex.Message + "</i>";
        }
    }
예제 #3
0
        public static void Send(string from, string to, string bcc, string subject, string body)
        {
            using (var client = new AmazonSimpleEmailServiceClient(Settings.AccessKey, Settings.Secret, RegionEndpoint.USWest2))
            {
                var request = new SendRawEmailRequest
                {
                    Source = from,
                    Destinations = new List<string> { to, bcc },
                    RawMessage = CreateMessage(from, to, bcc, subject, body)
                };

                client.SendRawEmail(request);
            }
        }
예제 #4
0
        public static void SendVerificationEmail(string emailaddress, string validation_guid)
        {
            const string VERIFICATION_DOMAIN = "https://nzixo03fx1.execute-api.us-west-2.amazonaws.com/prod/emailvalidation?verificationstring="; //TODO: Move this to our domain name prior to launch
            const string FROM = "*****@*****.**"; //TODO: Change to real domain name
            const string SUBJECT = "Please verify your email address";
            string TO = emailaddress;
            string mBase64EncodedGuid = Convert.ToBase64String(Encoding.UTF8.GetBytes(emailaddress + ":" + validation_guid));

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress("GEM CARRY EMAIL VERIFICATION", FROM));
            message.To.Add(new MailboxAddress("New Gamer", TO));
            message.Subject = SUBJECT;

            var builder = new BodyBuilder();
            builder.TextBody = string.Format("To activate your account, please click the following link to verifiy your email address {0}{1}", VERIFICATION_DOMAIN, mBase64EncodedGuid);
            builder.HtmlBody = string.Format("To activate your account, please click <a href={0}{1}> here</a> to verify your email address.",VERIFICATION_DOMAIN,mBase64EncodedGuid);

            message.Body = builder.ToMessageBody();

            var stream = new MemoryStream();
            message.WriteTo(stream);

            try
            {
                AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient();
                var request = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
                client.SendRawEmail(request);
            #if DEBUG
                logger.WriteLog(GameLogger.LogLevel.Debug, string.Format("Generating Validation Email for {0}.", emailaddress));
            #endif // DEBUG

            }
            catch (Exception ex)
            {
                logger.WriteLog(GameLogger.LogLevel.Error, ex.Message.ToString());
            }
        }
        /// <summary>
        /// Initiates the asynchronous execution of the SendRawEmail operation.
        /// <seealso cref="Amazon.SimpleEmail.IAmazonSimpleEmailService.SendRawEmail"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the SendRawEmail operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public async Task<SendRawEmailResponse> SendRawEmailAsync(SendRawEmailRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new SendRawEmailRequestMarshaller();
            var unmarshaller = SendRawEmailResponseUnmarshaller.GetInstance();
            var response = await Invoke<IRequest, SendRawEmailRequest, SendRawEmailResponse>(request, marshaller, unmarshaller, signer, cancellationToken)
                .ConfigureAwait(continueOnCapturedContext: false);
            return response;
        }
 /// <summary>
 ///     Sends a raw email.
 /// </summary>
 /// <param name="request">
 ///     A <see cref="SendRawEmailRequest" /> object.
 /// </param>
 /// <returns>
 ///     The unique <see cref="Message" /> ID for the email.
 /// </returns>
 internal string SendRawEmail(SendRawEmailRequest request)
 {
     SendRawEmailResponse response = _sesClient.SendRawEmail(request);
     return response != null && response.SendRawEmailResult != null ? response.SendRawEmailResult.MessageId : string.Empty;
 }
        /// <summary>
        /// <para>Sends an email message, with header and content specified by the client. The <c>SendRawEmail</c> action is useful for sending
        /// multipart MIME emails. The raw text of the message must comply with Internet email standards; otherwise, the message cannot be sent. </para>
        /// <para><b>IMPORTANT:</b> You can only send email from verified email addresses and domains. If you have not requested production access to
        /// Amazon SES, you must also verify every recipient email address except for the recipients provided by the Amazon SES mailbox simulator. For
        /// more information, go to the Amazon SES Developer Guide. </para> <para>The total size of the message cannot exceed 10 MB. This includes any
        /// attachments that are part of the message.</para> <para>Amazon SES has a limit on the total number of recipients per message: The combined
        /// number of To:, CC: and BCC: email addresses cannot exceed 50. If you need to send an email message to a larger audience, you can divide your
        /// recipient list into groups of 50 or fewer, and then call Amazon SES repeatedly to send the message to each group. </para> <para>For every
        /// message that you send, the total number of recipients (To:, CC: and BCC:) is counted against your <i>sending quota</i> - the maximum number
        /// of emails you can send in a 24-hour period. For information about your sending quota, go to the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html">Amazon SES Developer Guide</a> .
        /// </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the SendRawEmail service method on
        /// AmazonSimpleEmailService.</param>
        /// 
        /// <returns>The response from the SendRawEmail service method, as returned by AmazonSimpleEmailService.</returns>
        /// 
        /// <exception cref="T:Amazon.SimpleEmail.Model.MessageRejectedException" />
		public SendRawEmailResponse SendRawEmail(SendRawEmailRequest request)
        {
            var task = SendRawEmailAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                ExceptionDispatchInfo.Capture(e.InnerException).Throw();
                return null;
            }
        }
        /// <summary>
        /// Initiates the asynchronous execution of the SendRawEmail operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the SendRawEmail operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<SendRawEmailResponse> SendRawEmailAsync(SendRawEmailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new SendRawEmailRequestMarshaller();
            var unmarshaller = SendRawEmailResponseUnmarshaller.Instance;

            return InvokeAsync<SendRawEmailRequest,SendRawEmailResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
        /// <summary>
        /// Initiates the asynchronous execution of the SendRawEmail operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the SendRawEmail operation on AmazonSimpleEmailServiceClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSendRawEmail
        ///         operation.</returns>
        public IAsyncResult BeginSendRawEmail(SendRawEmailRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new SendRawEmailRequestMarshaller();
            var unmarshaller = SendRawEmailResponseUnmarshaller.Instance;

            return BeginInvoke<SendRawEmailRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
 /// <summary>
 /// Initiates the asynchronous execution of the SendRawEmail operation.
 /// <seealso cref="Amazon.SimpleEmail.AmazonSimpleEmailService.SendRawEmail"/>
 /// </summary>
 /// 
 /// <param name="sendRawEmailRequest">Container for the necessary parameters to execute the SendRawEmail operation on
 ///          AmazonSimpleEmailService.</param>
 /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
 /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 /// 
 /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndSendRawEmail
 ///         operation.</returns>
 public IAsyncResult BeginSendRawEmail(SendRawEmailRequest sendRawEmailRequest, AsyncCallback callback, object state)
 {
     return invokeSendRawEmail(sendRawEmailRequest, callback, state, false);
 }
예제 #11
0
        public void SendEmailWithAttachment()
        {
            var client = Amazon.AWSClientFactory.CreateAmazonSimpleEmailServiceClient(EmailProcessingConfigurationManager.Section.Amazon.Key, EmailProcessingConfigurationManager.Section.Amazon.Secret);

            MailMessage m = new MailMessage();
            var attachment = new Attachment("TextFile1.txt", "text/plain");
            attachment.TransferEncoding = TransferEncoding.QuotedPrintable;
            m.Attachments.Add(attachment);
            m.Body = "hello";
            m.Subject = "hello";
            m.To.Add("*****@*****.**");
            m.From = new MailAddress("*****@*****.**");

            var messageData = ConvertMailMessageToMemoryStream(m);
            RawMessage message = new RawMessage(messageData);
            SendRawEmailRequest request = new SendRawEmailRequest(message);
            var response = client.SendRawEmail(request);
        }
예제 #12
0
        public bool SendEmailWithAttachments(string AWSAccessKey, string AWSSecretKey, MailAddress From, MailAddress[] To, String Subject, System.Net.Mail.Attachment[] Attachments, String Text = null, String Html = null, MailAddress ReplyTo = null, MailAddress[] CCAddresses = null, MailAddress[] BCCAddresses = null)
        {
            AlternateView plainView = null;

            if (Text != null)
                plainView = AlternateView.CreateAlternateViewFromString(Text, Encoding.UTF8, "text/plain");

            AlternateView htmlView = null;

            if (Html != null)
                htmlView = AlternateView.CreateAlternateViewFromString(Html, Encoding.UTF8, "text/html");

            MailMessage mailMessage = new MailMessage();
            mailMessage.From = From;

            foreach (MailAddress toAdd in To ?? Enumerable.Empty<MailAddress>())
                mailMessage.To.Add(toAdd);

            foreach (MailAddress toCC in CCAddresses ?? Enumerable.Empty<MailAddress>())
                mailMessage.CC.Add(toCC);

            foreach (MailAddress toBcc in BCCAddresses ?? Enumerable.Empty<MailAddress>())
                mailMessage.Bcc.Add(toBcc);

            mailMessage.Subject = Subject;

            mailMessage.SubjectEncoding = Encoding.UTF8;

            if (ReplyTo != null)
            {
                mailMessage.ReplyTo = ReplyTo;
            }

            if (Text != null)
            {
                mailMessage.AlternateViews.Add(plainView);
            }

            if (Html != null)
            {
                mailMessage.AlternateViews.Add(htmlView);
            }

            foreach (System.Net.Mail.Attachment a in Attachments ?? Enumerable.Empty<System.Net.Mail.Attachment>())
            {
                mailMessage.Attachments.Add(a);
            }

            RawMessage rawMessage = new RawMessage();

            using (MemoryStream memoryStream = ConvertMailMessageToMemoryStream(mailMessage))
            {
                rawMessage.WithData(memoryStream);
            }

            SendRawEmailRequest request = new SendRawEmailRequest();

            request.WithRawMessage(rawMessage);

            request.WithDestinations(To.Select(a => a.Address));
            request.WithSource(From.Address);

            AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AWSAccessKey, AWSSecretKey);

            try
            {
                SendRawEmailResponse response = ses.SendRawEmail(request);
                SendRawEmailResult result = response.SendRawEmailResult;

                return true;
            }

            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("There was an error sending the e-mail: {0}", ex.Message));
                return false;
            }
        }
예제 #13
0
 public void enviarCorreoInstruc(JGA_PGS_NAV navieraCorreo, List<JGA_PGS_CXE> contactosNav, JGA_PGS_AGEN agenciaNacional, 
                          List<JGA_PGS_CXE> contactosAgenN, JGA_PGS_ENT embarcador, List<JGA_PGS_CXE> contactosEmb,
                          JGA_PGS_USR usuario, JGA_REPORTESPDF jga_reportespdf, Byte[] binary)
 {
     //acá empieza el método para enviar el correo electrónico a las personas pertinentes.
     //enviamos al método ISFEmail las listas de los datos para envio del correo a las personas correspondientes.
     var message = (MimeMessage)InstrucEmail(navieraCorreo, contactosNav, agenciaNacional, contactosAgenN, embarcador, contactosEmb, usuario, jga_reportespdf, binary);
     var stream = new MemoryStream();
     message.WriteTo(stream);
     //acá seteamos las credenciales que nos provee AWS para el envío de correos electrónicos.
     AWSCredentials credentials = new BasicAWSCredentials("AKIAI5LCJ5RFIUB4NJUQ", "XTRtXuW+mxYg2nZOtc7MnErmwJFRD5kgAKCPjmjU");
     //seteamos una variable con las credenciales y la zona que tenemos de AWS.
     using (var client = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(credentials, RegionEndpoint.USEast1))
     {
         var request = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
         //acá ejecutamos el envio del correo.
         var response = client.SendRawEmail(request);
     }
 }
예제 #14
0
 private void MessageNotif(JGA_PROYECCION proyeccion, JGA_PGS_ENT suplidor, List<JGA_PGS_CXE> contactosSup, JGA_PGS_ENT embarcador, List<JGA_PGS_CXE> contactosEmb, JGA_PGS_USR usuario)
 {
     //Se envía al método notifEmail las listas de los emails de los destinatarios.
     var message = (MimeMessage)notifEmail(proyeccion, suplidor, contactosSup, embarcador, contactosEmb, usuario);
     var stream = new MemoryStream();
     message.WriteTo(stream);
     //acá seteamos las credenciales que nos provee AWS para el envío de correos electrónicos.
     AWSCredentials credentials = new BasicAWSCredentials("AKIAI5LCJ5RFIUB4NJUQ", "XTRtXuW+mxYg2nZOtc7MnErmwJFRD5kgAKCPjmjU");
     //seteamos una variable con las credenciales y la zona que tenemos de AWS.
     using (var client = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(credentials, RegionEndpoint.USEast1))
     {
         var request = new SendRawEmailRequest { RawMessage = new RawMessage { Data = stream } };
         //acá ejecutamos el envio del correo.
         var response = client.SendRawEmail(request);
     }
 }
 /// <summary>
 /// Initiates the asynchronous execution of the SendRawEmail operation.
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the SendRawEmail operation on AmazonSimpleEmailServiceClient.</param>
 /// <param name="callback">An Action delegate that is invoked when the operation completes.</param>
 /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 public void SendRawEmailAsync(SendRawEmailRequest request, AmazonServiceCallback<SendRawEmailRequest, SendRawEmailResponse> callback, AsyncOptions options = null)
 {
     options = options == null?new AsyncOptions():options;
     var marshaller = new SendRawEmailRequestMarshaller();
     var unmarshaller = SendRawEmailResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<SendRawEmailRequest,SendRawEmailResponse> responseObject 
                     = new AmazonServiceResult<SendRawEmailRequest,SendRawEmailResponse>((SendRawEmailRequest)req, (SendRawEmailResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<SendRawEmailRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
        IAsyncResult invokeSendRawEmail(SendRawEmailRequest request, AsyncCallback callback, object state, bool synchronized)
        {
            var marshaller = new SendRawEmailRequestMarshaller();
            var unmarshaller = SendRawEmailResponseUnmarshaller.Instance;

            return Invoke(request, callback, state, synchronized, marshaller, unmarshaller, signer);
        }
예제 #17
0
        //From E-mail address must be verified through Amazon
        /// <summary>
        /// Text Only for now, no attachments yet.  Amazon SES is still in Beta
        /// </summary>
        /// <param name="AWSAccessKey">public key associated with our Amazon Account</param>
        /// <param name="AWSSecretKey">private key associated with our Amazon Account</param>
        /// <param name="From">Who is the e-mail from, this must be a verified e-mail address through Amazon</param>
        /// <param name="To">Who do you want to send the E-mail to, seperate multiple addresses with a comma</param>
        /// <param name="Subject">Subject of e-mail</param>
        /// <param name="Attachment">File Location of attachment.  PDF's, text files and images supported, seperate multiple addresses with a comma</param>
        /// <param name="Text">Plain text for e-mail, can be null</param>
        /// <param name="Html">Html view for e-mail, can be null</param>
        /// <param name="ReplyTo ">Email address for replies, can be null</param>
        /// <param name="CCAddresses ">ArrayList of strings for CC'd addresses</param>
        /// <param name="BCCAddresses ">ArrayList of strings for BCC'd addresses</param>
        public bool SendEmailWithAttachments(string AWSAccessKey, string AWSSecretKey, String From, String To, String Subject, String Attachment, String Text = null, String Html = null, String ReplyTo = null, ArrayList CCAddresses = null, ArrayList BCCAddresses = null)
        {
            AlternateView plainView = null;

            if (Text != null)
                plainView = AlternateView.CreateAlternateViewFromString(Text, Encoding.UTF8, "text/plain");

            AlternateView htmlView = null;

            if (Html != null)
                htmlView = AlternateView.CreateAlternateViewFromString(Html, Encoding.UTF8, "text/html");

            MailMessage mailMessage = new MailMessage();

            mailMessage.From = new MailAddress(From);

            List<String> toAddresses = To.Replace(", ", ",").Split(',').ToList();

            foreach (String toAddress in toAddresses)
            {
                mailMessage.To.Add(new MailAddress(toAddress));

            }

            if (CCAddresses != null)
            {
                foreach (String ccAddress in CCAddresses)
                {
                    mailMessage.CC.Add(new MailAddress(ccAddress));
                }
            }

            if (BCCAddresses != null)
            {
                foreach (String bccAddress in BCCAddresses)
                {
                    mailMessage.Bcc.Add(new MailAddress(bccAddress));
                }
            }
            mailMessage.Subject = Subject;

            mailMessage.SubjectEncoding = Encoding.UTF8;

            if (ReplyTo != null)
            {
                mailMessage.ReplyTo = new MailAddress(ReplyTo);
            }

            if (Text != null)
            {
                mailMessage.AlternateViews.Add(plainView);
            }

            if (Html != null)
            {
                mailMessage.AlternateViews.Add(htmlView);
            }

            // Attachment Fix
            //System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(Attachment);
            //mailMessage.Attachments.Add(a);
            foreach (String attachment in Attachment.Replace(", ", ",").Split(',').ToList())
            {
                System.Net.Mail.Attachment a = new System.Net.Mail.Attachment(attachment);
                mailMessage.Attachments.Add(a);
            }

            RawMessage rawMessage = new RawMessage();

            using (MemoryStream memoryStream = ConvertMailMessageToMemoryStream(mailMessage))
            {
                rawMessage.WithData(memoryStream);
            }

            SendRawEmailRequest request = new SendRawEmailRequest();

            request.WithRawMessage(rawMessage);

            request.WithDestinations(toAddresses);
            request.WithSource(From);

            AmazonSimpleEmailService ses = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(AWSAccessKey, AWSSecretKey);

            try
            {
                SendRawEmailResponse response = ses.SendRawEmail(request);
                SendRawEmailResult result = response.SendRawEmailResult;

                return true;
            }

            catch
            {
                return false;
            }
        }
 IAsyncResult invokeSendRawEmail(SendRawEmailRequest sendRawEmailRequest, AsyncCallback callback, object state, bool synchronized)
 {
     IRequest irequest = new SendRawEmailRequestMarshaller().Marshall(sendRawEmailRequest);
     var unmarshaller = SendRawEmailResponseUnmarshaller.GetInstance();
     AsyncResult result = new AsyncResult(irequest, callback, state, synchronized, signer, unmarshaller);
     Invoke(result);
     return result;
 }
  /// <summary>
  /// <para>Sends an email message, with header and content specified by the
  /// client. The <c>SendRawEmail</c> action is useful for sending multipart
  /// MIME emails, with attachments or inline content.</para> <para>The raw
  /// text of the message must comply with Internet email standards;
  /// otherwise, the message cannot be sent. For more information, go to
  /// the Amazon SES Developer Guide.</para>
  /// </summary>
  /// 
  /// <param name="sendRawEmailRequest">Container for the necessary
  ///           parameters to execute the SendRawEmail service method on
  ///           AmazonSimpleEmailService.</param>
  /// 
  /// <returns>The response from the SendRawEmail service method, as
  ///         returned by AmazonSimpleEmailService.</returns>
  /// 
  /// <exception cref="MessageRejectedException"/>
 public SendRawEmailResponse SendRawEmail(SendRawEmailRequest sendRawEmailRequest) 
 {           
     IRequest<SendRawEmailRequest> request = new SendRawEmailRequestMarshaller().Marshall(sendRawEmailRequest);
     SendRawEmailResponse response = Invoke<SendRawEmailRequest, SendRawEmailResponse> (request, this.signer, SendRawEmailResponseUnmarshaller.GetInstance());
     return response;
 }
 /// <summary>
 /// <para>Sends an email message, with header and content specified by the client. The <c>SendRawEmail</c> action is useful for sending
 /// multipart MIME emails. The raw text of the message must comply with Internet email standards; otherwise, the message cannot be sent. </para>
 /// <para><b>IMPORTANT:</b>If you have not yet requested production access to Amazon SES, then you will only be able to send email to and from
 /// verified email addresses and domains. For more information, go to the Amazon SES Developer Guide. </para> <para>The total size of the
 /// message cannot exceed 10 MB. This includes any attachments that are part of the message.</para> <para>Amazon SES has a limit on the total
 /// number of recipients per message: The combined number of To:, CC: and BCC: email addresses cannot exceed 50. If you need to send an email
 /// message to a larger audience, you can divide your recipient list into groups of 50 or fewer, and then call Amazon SES repeatedly to send the
 /// message to each group. </para> <para>For every message that you send, the total number of recipients (To:, CC: and BCC:) is counted against
 /// your <i>sending quota</i> - the maximum number of emails you can send in a 24-hour period. For information about your sending quota, go to
 /// the "Managing Your Sending Activity" section of theAmazon SES Developer Guide. </para>
 /// </summary>
 /// 
 /// <param name="sendRawEmailRequest">Container for the necessary parameters to execute the SendRawEmail service method on
 ///          AmazonSimpleEmailService.</param>
 /// 
 /// <returns>The response from the SendRawEmail service method, as returned by AmazonSimpleEmailService.</returns>
 /// 
 /// <exception cref="MessageRejectedException"/>
 public SendRawEmailResponse SendRawEmail(SendRawEmailRequest sendRawEmailRequest)
 {
     IAsyncResult asyncResult = invokeSendRawEmail(sendRawEmailRequest, null, null, true);
     return EndSendRawEmail(asyncResult);
 }
예제 #21
0
        public object Execute(ExecutorContext context)
        {
            System.IO.MemoryStream _RawMessage_DataStream = null;

            try
            {
                var cmdletContext = context as CmdletContext;
                // create request
                var request = new Amazon.SimpleEmail.Model.SendRawEmailRequest();

                if (cmdletContext.ConfigurationSetName != null)
                {
                    request.ConfigurationSetName = cmdletContext.ConfigurationSetName;
                }
                if (cmdletContext.Destination != null)
                {
                    request.Destinations = cmdletContext.Destination;
                }
                if (cmdletContext.FromArn != null)
                {
                    request.FromArn = cmdletContext.FromArn;
                }

                // populate RawMessage
                var requestRawMessageIsNull = true;
                request.RawMessage = new Amazon.SimpleEmail.Model.RawMessage();
                System.IO.MemoryStream requestRawMessage_rawMessage_Data = null;
                if (cmdletContext.RawMessage_Data != null)
                {
                    _RawMessage_DataStream            = new System.IO.MemoryStream(cmdletContext.RawMessage_Data);
                    requestRawMessage_rawMessage_Data = _RawMessage_DataStream;
                }
                if (requestRawMessage_rawMessage_Data != null)
                {
                    request.RawMessage.Data = requestRawMessage_rawMessage_Data;
                    requestRawMessageIsNull = false;
                }
                // determine if request.RawMessage should be set to null
                if (requestRawMessageIsNull)
                {
                    request.RawMessage = null;
                }
                if (cmdletContext.ReturnPathArn != null)
                {
                    request.ReturnPathArn = cmdletContext.ReturnPathArn;
                }
                if (cmdletContext.Source != null)
                {
                    request.Source = cmdletContext.Source;
                }
                if (cmdletContext.SourceArn != null)
                {
                    request.SourceArn = cmdletContext.SourceArn;
                }
                if (cmdletContext.Tag != null)
                {
                    request.Tags = cmdletContext.Tag;
                }

                CmdletOutput output;

                // issue call
                var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
                try
                {
                    var    response       = CallAWSServiceOperation(client, request);
                    object pipelineOutput = null;
                    pipelineOutput = cmdletContext.Select(response, this);
                    output         = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };
                }
                catch (Exception e)
                {
                    output = new CmdletOutput {
                        ErrorResponse = e
                    };
                }

                return(output);
            }
            finally
            {
                if (_RawMessage_DataStream != null)
                {
                    _RawMessage_DataStream.Dispose();
                }
            }
        }
        /// <summary>
        /// Sends an email message, with header and content specified by the client. The <code>SendRawEmail</code>
        /// action is useful for sending multipart MIME emails. The raw text of the message must
        /// comply with Internet email standards; otherwise, the message cannot be sent. 
        /// 
        ///  
        /// <para>
        /// There are several important points to know about <code>SendRawEmail</code>:
        /// </para>
        ///  <ul> <li> 
        /// <para>
        /// You can only send email from verified email addresses and domains; otherwise, you
        /// will get an "Email address not verified" error. If your account is still in the Amazon
        /// SES sandbox, you must also verify every recipient email address except for the recipients
        /// provided by the Amazon SES mailbox simulator. For more information, go to the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html">Amazon
        /// SES Developer Guide</a>.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// The total size of the message cannot exceed 10 MB. This includes any attachments that
        /// are part of the message.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// Amazon SES has a limit on the total number of recipients per message. The combined
        /// number of To:, CC: and BCC: email addresses cannot exceed 50. If you need to send
        /// an email message to a larger audience, you can divide your recipient list into groups
        /// of 50 or fewer, and then call Amazon SES repeatedly to send the message to each group.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// The To:, CC:, and BCC: headers in the raw message can contain a group list. Note that
        /// each recipient in a group list counts towards the 50-recipient limit.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// Amazon SES overrides any Message-ID and Date headers you provide.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// For every message that you send, the total number of recipients (To:, CC: and BCC:)
        /// is counted against your sending quota - the maximum number of emails you can send
        /// in a 24-hour period. For information about your sending quota, go to the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html">Amazon
        /// SES Developer Guide</a>.
        /// </para>
        ///  </li> <li> 
        /// <para>
        /// If you are using sending authorization to send on behalf of another user, <code>SendRawEmail</code>
        /// enables you to specify the cross-account identity for the email's "Source," "From,"
        /// and "Return-Path" parameters in one of two ways: you can pass optional parameters
        /// <code>SourceArn</code>, <code>FromArn</code>, and/or <code>ReturnPathArn</code> to
        /// the API, or you can include the following X-headers in the header of your raw email:
        /// </para>
        ///  <ul> <li> 
        /// <para>
        ///  <code>X-SES-SOURCE-ARN</code> 
        /// </para>
        ///  </li> <li> 
        /// <para>
        ///  <code>X-SES-FROM-ARN</code> 
        /// </para>
        ///  </li> <li> 
        /// <para>
        ///  <code>X-SES-RETURN-PATH-ARN</code> 
        /// </para>
        ///  </li> </ul> <important> 
        /// <para>
        /// Do not include these X-headers in the DKIM signature, because they are removed by
        /// Amazon SES before sending the email.
        /// </para>
        ///  </important> 
        /// <para>
        /// For the most common sending authorization use case, we recommend that you specify
        /// the <code>SourceIdentityArn</code> and do not specify either the <code>FromIdentityArn</code>
        /// or <code>ReturnPathIdentityArn</code>. (The same note applies to the corresponding
        /// X-headers.) If you only specify the <code>SourceIdentityArn</code>, Amazon SES will
        /// simply set the "From" address and the "Return Path" address to the identity specified
        /// in <code>SourceIdentityArn</code>. For more information about sending authorization,
        /// see the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/sending-authorization.html">Amazon
        /// SES Developer Guide</a>.
        /// </para>
        ///  </li> </ul>
        /// </summary>
        /// <param name="request">Container for the necessary parameters to execute the SendRawEmail service method.</param>
        /// 
        /// <returns>The response from the SendRawEmail service method, as returned by SimpleEmailService.</returns>
        /// <exception cref="Amazon.SimpleEmail.Model.ConfigurationSetDoesNotExistException">
        /// Indicates that the configuration set does not exist.
        /// </exception>
        /// <exception cref="Amazon.SimpleEmail.Model.MailFromDomainNotVerifiedException">
        /// Indicates that the message could not be sent because Amazon SES could not read the
        /// MX record required to use the specified MAIL FROM domain. For information about editing
        /// the custom MAIL FROM domain settings for an identity, see the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/mail-from-edit.html">Amazon
        /// SES Developer Guide</a>.
        /// </exception>
        /// <exception cref="Amazon.SimpleEmail.Model.MessageRejectedException">
        /// Indicates that the action failed, and the message could not be sent. Check the error
        /// stack for more information about what caused the error.
        /// </exception>
        public SendRawEmailResponse SendRawEmail(SendRawEmailRequest request)
        {
            var marshaller = new SendRawEmailRequestMarshaller();
            var unmarshaller = SendRawEmailResponseUnmarshaller.Instance;

            return Invoke<SendRawEmailRequest,SendRawEmailResponse>(request, marshaller, unmarshaller);
        }
예제 #23
0
 private Amazon.SimpleEmail.Model.SendRawEmailResponse CallAWSServiceOperation(IAmazonSimpleEmailService client, Amazon.SimpleEmail.Model.SendRawEmailRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Simple Email Service (SES)", "SendRawEmail");
     try
     {
         #if DESKTOP
         return(client.SendRawEmail(request));
         #elif CORECLR
         return(client.SendRawEmailAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
        /// <summary>
        /// <para>Sends an email message, with header and content specified by the client. The <c>SendRawEmail</c> action is useful for sending
        /// multipart MIME emails. The raw text of the message must comply with Internet email standards; otherwise, the message cannot be sent. </para>
        /// <para><b>IMPORTANT:</b> You can only send email from verified email addresses and domains. If you have not requested production access to
        /// Amazon SES, you must also verify every recipient email address except for the recipients provided by the Amazon SES mailbox simulator. For
        /// more information, go to the Amazon SES Developer Guide. </para> <para>The total size of the message cannot exceed 10 MB. This includes any
        /// attachments that are part of the message.</para> <para>Amazon SES has a limit on the total number of recipients per message: The combined
        /// number of To:, CC: and BCC: email addresses cannot exceed 50. If you need to send an email message to a larger audience, you can divide your
        /// recipient list into groups of 50 or fewer, and then call Amazon SES repeatedly to send the message to each group. </para> <para>For every
        /// message that you send, the total number of recipients (To:, CC: and BCC:) is counted against your <i>sending quota</i> - the maximum number
        /// of emails you can send in a 24-hour period. For information about your sending quota, go to the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/manage-sending-limits.html">Amazon SES Developer Guide</a> .
        /// </para>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the SendRawEmail service method on
        /// AmazonSimpleEmailService.</param>
        /// 
        /// <returns>The response from the SendRawEmail service method, as returned by AmazonSimpleEmailService.</returns>
        /// 
        /// <exception cref="T:Amazon.SimpleEmail.Model.MessageRejectedException" />
		public SendRawEmailResponse SendRawEmail(SendRawEmailRequest request)
        {
            var task = SendRawEmailAsync(request);
            try
            {
                return task.Result;
            }
            catch(AggregateException e)
            {
                throw e.InnerException;
            }
        }
예제 #25
0
        /// <summary>
        /// Method to send email through cloud service. Please make sure that the attachements are of supported types.
        /// If MailMessage has LinkedResources associated with alternate views, they will be removed. Amazon SES currently
        /// requires content disposition for linked resources, which .Net does not support.
        /// </summary>
        /// <param name="mailMessage">.Net MailMessage</param>        
        public void SendBulkEmail(MailMessage mailMessage)
        {
            //Create a temp unique folder under WorkingTempFolder
            string currentWorkingFolder = Path.Combine(this.cloudServiceConfigProvider.WorkingTempFolder, System.Guid.NewGuid().ToString("N"));

            try
            {
                if (mailMessage == null)
                    throw new CloudServiceException("Mail message must be provided.");

                if (mailMessage.To.Count == 0)
                    throw new CloudServiceException("To address is required.");

                if (mailMessage.From == null || string.IsNullOrEmpty(mailMessage.From.Address))
                    throw new CloudServiceException("From address is required.");

                if (!Directory.Exists(this.cloudServiceConfigProvider.WorkingTempFolder))
                    throw new CloudServiceConfigException("WorkingTempFolder specified does not exist.");

                DirectoryInfo dInfo = Directory.CreateDirectory(currentWorkingFolder);

                //Clear linked resources (Amazon has a glitch by requiring content-disposition for LinkedResource)
                foreach (AlternateView av in mailMessage.AlternateViews)
                {
                    av.LinkedResources.Clear();
                }

                //Setup content disposition for attachments
                //Amazon needs content disposition
                foreach (Attachment attachment in mailMessage.Attachments)
                {
                    if (attachment.ContentDisposition != null)
                    {
                        attachment.ContentDisposition.Inline = false;

                        if (attachment.ContentStream != null)
                            attachment.ContentDisposition.Size = attachment.ContentStream.Length;
                    }
                }

                //Create smpt client
                SmtpClient client = new SmtpClient();
                client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                client.PickupDirectoryLocation = currentWorkingFolder;

                client.Send(mailMessage);

                //Create AWS Client
                AmazonSimpleEmailService amazonSes = AWSClientFactory.CreateAmazonSimpleEmailServiceClient(this.cloudServiceConfigProvider.AWSAccessKeyId, this.cloudServiceConfigProvider.AWSSecretKey);

                //At this point the email is created in the working folder. Ready one at a time and send to amazon
                foreach (FileInfo fInfo in dInfo.GetFiles())
                {
                    byte[] emailRawContent = File.ReadAllBytes(fInfo.FullName);
                    using (MemoryStream msEmail = new MemoryStream(emailRawContent, 0, emailRawContent.Length))
                    {
                        RawMessage rawMessage = new RawMessage(msEmail);

                        SendRawEmailRequest sendRawEmailRequest = new SendRawEmailRequest(rawMessage);
                        SendRawEmailResponse sendRawEmailRes = amazonSes.SendRawEmail(sendRawEmailRequest);
                    }
                }
            }
            catch (CloudServiceException aex)
            {
                throw aex;
            }
            catch (Exception ex)
            {
                throw new CloudServiceException(ex, "Error occured when sending bulk email.");
            }
            finally
            {
                if(!this.cloudServiceConfigProvider.IsTraceMode == !string.IsNullOrEmpty(currentWorkingFolder))
                {
                    if (Directory.Exists(currentWorkingFolder))
                    {
                        foreach (string file in Directory.GetFiles(currentWorkingFolder))
                        {
                            try
                            {
                                if (File.Exists(file))
                                    File.Delete(file);
                            }
                            catch
                            {
                                ///TODO: Add log once moved to common library
                            }
                        }

                        try
                        {
                            Directory.Delete(currentWorkingFolder);
                        }
                        catch
                        {
                            ///TODO: Add log once moved to common library
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Initiates the asynchronous execution of the SendRawEmail operation.
        /// <seealso cref="Amazon.SimpleEmail.IAmazonSimpleEmailService.SendRawEmail"/>
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the SendRawEmail operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
		public Task<SendRawEmailResponse> SendRawEmailAsync(SendRawEmailRequest request, CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new SendRawEmailRequestMarshaller();
            var unmarshaller = SendRawEmailResponseUnmarshaller.GetInstance();
            return Invoke<IRequest, SendRawEmailRequest, SendRawEmailResponse>(request, marshaller, unmarshaller, signer, cancellationToken);
        }
        /// <summary>
        ///     <see cref="Send" /> this message.
        /// </summary>
        /// <returns>
        ///     <see langword="true" /> if it succeeds, <see langword="false" /> if it fails.
        /// </returns>
        internal bool Send()
        {
            _email.MessageId = string.Empty;

            try
            {
                var mailMessage = new MailMessage { From = new MailAddress(_email.FromAddress) };

                foreach (string toAddress in _email.ToAddressList)
                    mailMessage.To.Add(new MailAddress(toAddress));

                foreach (string ccAddress in _email.CcAddressList)
                    mailMessage.CC.Add(new MailAddress(ccAddress));

                foreach (string bccAddress in _email.BccAddressList)
                    mailMessage.Bcc.Add(new MailAddress(bccAddress));

                mailMessage.Subject = _email.MessageSubject;
                mailMessage.SubjectEncoding = Encoding.UTF8;
                mailMessage.AlternateViews.Add(
                    _email.HTML
                        ? AlternateView.CreateAlternateViewFromString(_email.MessageBody, Encoding.UTF8, "text/html")
                        : AlternateView.CreateAlternateViewFromString(_email.MessageBody, Encoding.UTF8, "text/plain"));

                var attachment = new Attachment(_email.AttachmentFilePath)
                {
                    ContentType = new ContentType("application/octet-stream")
                };

                ContentDisposition disposition = attachment.ContentDisposition;
                disposition.DispositionType = "attachment";
                disposition.CreationDate = File.GetCreationTime(_email.AttachmentFilePath);
                disposition.ModificationDate = File.GetLastWriteTime(_email.AttachmentFilePath);
                disposition.ReadDate = File.GetLastAccessTime(_email.AttachmentFilePath);
                mailMessage.Attachments.Add(attachment);

                var rawMessage = new RawMessage();

                using (MemoryStream memoryStream = ConvertMailMessageToMemoryStream(mailMessage))
                    rawMessage.WithData(memoryStream);

                var request = new SendRawEmailRequest
                {
                    RawMessage = rawMessage,
                    Destinations = _email.Destination.ToAddresses,
                    Source = _email.FromAddress
                };

                using (var client = new Client(_email.Credentials))
                {
                    _email.MessageId = client.SendRawEmail(request);
                }

                return !_email.ErrorExists;
            }
            catch (AmazonSimpleEmailServiceException ex)
            {
                return _email.SetErrorMessage(
                    string.Format(
                        "AWS Simple Email Service Exception\n\nError Type: {0}\n" +
                        "Error Code: {1}\nRequest Id: {2}\nStatus Code: {3}\n\n{4}",
                        ex.ErrorType, ex.ErrorCode, ex.RequestId, ex.StatusCode, ex));
            }
            catch (AmazonClientException ex)
            {
                return _email.SetErrorMessage(ex.ToString());
            }
            catch (Exception ex)
            {
                return _email.SetErrorMessage(ex.ToString());
            }
        }