通过亚马逊ses发送html模板

时间:2013-07-31 09:27:16

标签: c# .net amazon amazon-ses

我正在使用以下代码发送计划文本,但它不能在html模板中运行..

    static void Main(string[] args)
    {
        String username = "test";  // Replace with your SMTP username.
        String password = "test";  // Replace with your SMTP password.
        String host = "email-smtp.us-east-1.amazonaws.com";
        int port = 25;

        using (var client = new System.Net.Mail.SmtpClient(host, port))
        {
            client.Credentials = new System.Net.NetworkCredential(username, password);
            client.EnableSsl = true;

            client.Send
            (
                      "sales@imagedb.com",  // Replace with the sender address.
                      "rohit@imagedb.com",    // Replace with the recipient address.
                      "Testing Amazon SES through SMTP",
                      "This email was delivered through Amazon SES via the SMTP end point."
            );
        }

1 个答案:

答案 0 :(得分:6)

您需要在.NET SmtpClient中使用AlternateView来发送HTML消息。邮件客户端将呈现它可以支持的适当视图。

以下是一段代码片段,演示了如何使用文本视图和HTML视图创建消息,然后通过Amazon SES发送消息。

        string host = "email-smtp.us-east-1.amazonaws.com";
        int port = 25;

        var credentials = new NetworkCredential("ses-smtp-username", "ses-smtp-password");
        var sender = new MailAddress("sender@example.com", "Message Sender");
        var recipientTo = new MailAddress("recipient+one@example.com", "Recipient One");
        var subject = "HTML and TXT views";

        var htmlView = AlternateView.CreateAlternateViewFromString("<p>This message is <code>formatted</code> with <strong>HTML</strong>.</p>", Encoding.UTF8, MediaTypeNames.Text.Html);
        var txtView = AlternateView.CreateAlternateViewFromString("This is a plain text message.", Encoding.UTF8, MediaTypeNames.Text.Plain);

        var message = new MailMessage();
        message.Subject = subject;
        message.From = sender;
        message.To.Add(recipientTo);
        message.AlternateViews.Add(txtView);
        message.AlternateViews.Add(htmlView);

        using (var client = new SmtpClient(host, port))
        {
            client.Credentials = credentials;
            client.EnableSsl = true;

            client.Send(message);
        }