我在亚马逊ec2上托管我的网络应用程序,它是用.net mvc2编写的。目前使用gmailsmtp发送电子邮件。由于谷歌的启动电子邮件配额,每天发送的电子邮件不能超过500封。所以决定移动亚马逊服务器。如何将amazon-ses与asp.net mvc2结合使用?配置等如何?电子邮件将通过gmail发送吗?因为我们的电子邮件提供商是gmail。等等
通过亚马逊发送电子邮件是一个正确的决定。因为当你搬到亚马逊时,你每天将立即获得2000封免费电子邮件,这比谷歌应用程序每天500封电子邮件的配额还要多。
循序渐进:
- 转到http://aws.amazon.com/ses然后单击注册亚马逊SES
- 获取您的AWS访问标识符
- 验证您的电子邮件地址-电子邮件您将通过其发送电子邮件。你需要在上安装perl包您的计算机测试电子邮件功能
- 包括:amazones.com到您的dns记录
逐步编制文档。http://docs.aws.amazon.com/ses/latest/DeveloperGuide/getting-started.html
codeplex上有一个亚马逊SES(简单电子邮件服务)C#包装器,你可以使用这个包装器发送电子邮件。
亚马逊SES C#包装
最简单的方法是通过Nuget下载SDK(包名为AWSSDK)或从亚马逊网站下载SDK。从他们网站下载的sdk有一个示例项目,向您展示如何调用他们的API来发送电子邮件。唯一的配置是插入你的api密钥。最棘手的部分是验证您的发送地址(以及任何测试收件人),但他们也是发送测试消息的API调用。然后,您需要登录并验证这些电子邮件地址。电子邮件将通过亚马逊发送(这就是重点),但发件人电子邮件地址可以是你的gmail地址。
@gandil我创建了这个非常简单的代码来发送电子邮件
using Amazon;
using Amazon.SimpleEmail;
using Amazon.SimpleEmail.Model;
using System.IO;
namespace SendEmail
{
class Program
{
static void Main(string[] args)
{
//Remember to enter your (AWSAccessKeyID, AWSSecretAccessKey) if not using and IAM User with credentials assigned to your instance and your RegionEndpoint
using (var client = new AmazonSimpleEmailServiceClient("YourAWSAccessKeyID", "YourAWSSecretAccessKey", RegionEndpoint.USEast1))
{
var emailRequest = new SendEmailRequest()
{
Source = "FROMADDRESS@TEST.COM",
Destination = new Destination(),
Message = new Message()
};
emailRequest.Destination.ToAddresses.Add("TOADDRESS@TEST.COM");
emailRequest.Message.Subject = new Content("Hello World");
emailRequest.Message.Body = new Body(new Content("Hello World"));
client.SendEmail(emailRequest);
}
}
}
}
你可以在这里找到代码https://github.com/gianluis90/amazon-send-email
- 从internet下载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。将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("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;
}
}
- 使用以上类别向任何人发送邮件,并替换附件和模板变体(可选)//调用此方法发送电子邮件
公共字符串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 = @"TemplatesMyUserNotification.html"; //add file attachment / add your file ... emailContaint.AttachedFile = "ExcelReportreport.pdf"; //Note :In case of template //if youe want to replace variables in run time //just add replacements like <%FirstName%> , <%OrderNo%> , in HTML Template //if you are using some varibales in template then add // Hold first name.. var FirstName = "User First Name"; // Hold email.. var OrderNo = 1236; //firstname replacement.. emailContaint.Replacements.Add("FirstName", FirstName.ToString()); emailContaint.Replacements.Add("OrderNo", OrderNo.ToString()); // endregion option email stuff //user OrderNo replacement... emailContaint.To.Add(new MailAddress("TOEmail@gmail.com")); //mail sent status bool isSent = emailContaint.SendMail(emailStuff); if(isSent) { emailStatus = "Success"; } else { emailStatus = "Fail"; } return emailStatus ; }
以下是我如何发送带有附件的电子邮件
public static void SendMailSynch(string file1, string sentFrom, List<string> recipientsList, string subject, string body)
{
string smtpClient = "email-smtp.us-east-1.amazonaws.com"; //Correct it
string conSMTPUsername = "<USERNAME>";
string conSMTPPassword = "<PWD>";
string username = conSMTPUsername;
string password = conSMTPPassword;
// Configure the client:
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(smtpClient);
client.Port = 25;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Credentials = credentials;
// Create the message:
var mail = new System.Net.Mail.MailMessage();
mail.From = new MailAddress(sentFrom);
foreach (string recipient in recipientsList)
{
mail.To.Add(recipient);
}
mail.Bcc.Add("test@test.com");
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
Attachment attachment1 = new Attachment(file1, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment1.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file1);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file1);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file1);
mail.Attachments.Add(attachment1);
client.Send(mail);
}