Invia e -mail da Amazon SES nell'app ASP.NET MVC
-
29-10-2019 - |
Domanda
Ospito la mia app Web scritta in .NET MVC2 su Amazon EC2. Currrently Utilizzare Gmail SMTP per inviare e -mail. Beacuse di Google per la quota di posta elettronica di avvio non può inviare più di 500 e -mail al giorno. Quindi decidi di spostare Amazon SES. Come può usare Amazon SES con ASP.NET MVC2? Che ne dici di configurazione ecc.? L'e -mail verrà inviata tramite Gmail? Perché il nostro provider di posta elettronica è Gmail. eccetera.
Soluzione
Invia e -mail tramite Amazon è una decisione giusta. Perché quando ti trasferisci ad Amazon riceverai immediatamente 2000 e -mail gratuitamente al giorno, il che è maggiore delle app GOOGLA 500 quote di posta elettronica al giorno.
Passo dopo passo:
- Vai a http://aws.amazon.com/sesE fai clic su Iscriviti per Amazon SES.
- Per ottenere i tuoi identificatori di accesso AWS
- Verifica il tuo indirizzo e -mail - e -mail che invierai e -mail tramite. Sono necessari pacchetti perl installati sul tuo computer per testare le funzionalità e -mail.
- Includi: Amazonses.com per il tuo record DNS.
Documentazione passo -passo.http://docs.aws.amazon.com/ses/latest/develingerguide/getting-started.html
Esiste un wrapper C# Amazon SES (Simple Email Service) C# su CodePlex È possibile utilizzare questo wrapper per inviare e -mail.
Altri suggerimenti
Il modo più semplice è scaricare l'SDK tramite Nuget (il pacchetto si chiama AWSSDK) o scaricare l'SDK dal sito di Amazon. Il download di SDK dal loro sito ha un progetto di esempio che mostra come chiamare la loro API per inviare e -mail. L'unica configurazione è collegare i tasti API. La parte più difficile è verificare l'indirizzo di invio (e qualsiasi ricevimento di test) ma la loro è una chiamata API anche lì per inviare il messaggio di prova. Dovrai quindi accedere e verificare quegli indirizzi e -mail. L'e -mail verrà inviata tramite Amazon (che è il punto dell'intero) ma l'indirizzo e -mail può essere il tuo indirizzo Gmail.
- Scarica file AWSSDK.DLL da Internet Utilizzare i seguenti nomi-spazi
using Amazon; using Amazon.SimpleEmail; using Amazon.SimpleEmail.Model; using System.Net.Mail;
2. Aggiungi a Web Config ...
<appSettings>
<add key="AWSAccessKey" value="Your AWS Access Key" />
<add key="AWSSecretKey" value="Your AWS secret Key" />
</appSettings>
3. Aggiungi una classe di AwsemailSevice al tuo progetto che consentirà di inviare posta tramite 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("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;
}
}
- Utilizzare la classe sopra per inviare posta chiunque abbia la sostituzione dei varibales allegati e modello (è facoltativo) // chiama questo metodo per inviare la tua e -mail
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 Ho creato questo codice molto semplice per inviare e -mail
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);
}
}
}
}
Puoi trovare il codice qui https://github.com/gianluis90/amazon-send-email