简体   繁体   English

使用mailgun发送带有html标签的电子邮件

[英]Send email with html tags using mailgun

I have this code for sending email using mailgun:我有使用mailgun发送电子邮件的代码:

public async Task SendMail(string replyTo, string to, string cc, string subject, string message)
    {
        var smtpServer = config[ConfigurationSMTP_Server];
        var smtpPort = Convert.ToInt32(config[Configuration_SMTP_Port]);
        var smtpUsername = config[Configuration.SMTP_Username];
        var smtpPassword = config[Configuration.SMTP_Password];

        MimeMessage mail = new MimeMessage();

        mail.From.Add(new MailboxAddress(String.Empty, smtpUsername));
        
        mail.ReplyTo.Add(new MailboxAddress(String.Empty, replyTo));
   
        mail.To.Add(new MailboxAddress(String.Empty, to));
        
        mail.Cc.Add(new MailboxAddress(String.Empty, cc));
       

        mail.Subject = subject;
        mail.Body = new TextPart("plain")
        {
            Text = message,
        };

        using (var client = new SmtpClient())
        {
            client.Connect(smtpServer, smtpPort, false);
            client.AuthenticationMechanisms.Remove("XOAUTH2");

            client.Authenticate(smtpUsername, smtpPassword);

            await client.SendAsync(mail);
            client.Disconnect(true);
        }

    }

It works but the br, p html tags doesn't seem to apply to the mail.它有效,但 br, p html 标签似乎不适用于邮件。 How can I refractor this to do so?我怎么能折射这个呢?

This did the trick这成功了

mail.Body = new TextPart(MimeKit.Text.TextFormat.Html)
{
            Text = message,
};

You can use the recipient-variables and v: functionality provided by Mailgun.您可以使用 Mailgun 提供的收件人变量和 v: 功能。

For example following is a JSON string -例如以下是一个 JSON 字符串 -

r = '{
"foo@boo.com": {"FirstName": "Toby","LastName": "Moon"},
"yoo@too.com": {"FirstName": "Bobby","LastName": "Sun"}
}'

Assign it to recipient-variables while calling the API.在调用 API 时将其分配给收件人变量。

res = requests.post(
        "API url",
        auth=("api", "API key"),   
        data={  
                "from": "<yourdomain@yourdomain.com">,  
                "to": ["List of Emails"],
                "subject": "Test Email",
                "recipient-variables": r,
                'v:FirstName':'%recipient.FirstName%',
                'v:LastName':'%recipient.LastName%',
        })
    print(res)

You can then use %recipient.value% anywhere to reference it dynamically.然后,您可以在任何地方使用 %recipient.value% 来动态引用它。

The following link has steps included - Mailgun Recipient Variables以下链接包含步骤 - Mailgun 收件人变量

The above is an example in Python.以上是Python中的一个例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM