如何使用 ASP .NET Core 7 发送 HTML 电子邮件

问题描述 投票:0回答:1

我需要使用 SMTP 和 MailKit 使用 ASP .NET Core 7 发送带有 HTML 标签的电子邮件。我已经发送了带有最少 html 标签的电子邮件,例如 .但我需要发送带有图像(徽标)的页眉和页脚。 这就是API方案。 API request

我需要发送如下 HTML 电子邮件 Email sample

我插入了这样的html代码sending email

但是它给出了这样的错误。 Error I encounter

我的问题是我不知道如何在包含 CSS 和图像的正文中插入 html 代码。如何发送这样的电子邮件?这个错误是由于我编写的API代码导致的还是有其他方法可以做到这一点?

这是我在.net中编写的电子邮件服务代码

using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Text;

namespace AgrarianTradeSystemWebAPI.Services.EmailService
{
    public class EmailService : IEmailService
    {
        private readonly IConfiguration _config;

        public EmailService(IConfiguration config)
        {
            _config = config;
        }

        public void SendEmail(EmailDto request)
        {
            var email = new MimeMessage();
            email.From.Add(MailboxAddress.Parse(_config.GetSection("EmailConfig:EmailUsername").Value));
            email.To.Add(MailboxAddress.Parse(request.To));
            email.Subject = request.Subject;
            email.Body = new TextPart(TextFormat.Html) { Text = request.Body };
            using var smtp = new SmtpClient();
            smtp.Connect(_config.GetSection("EmailConfig:EmailHost").Value, 587, SecureSocketOptions.StartTls);
            smtp.Authenticate(_config.GetSection("EmailConfig:EmailUsername").Value, _config.GetSection("EmailConfig:EmailPassword").Value);
            smtp.Send(email);
            smtp.Disconnect(true);
        }
    }
}

我为此使用的 DTO 是

public class EmailDto
{
    public string To { get; set; } = string.Empty;
    public string Subject { get; set; } = string.Empty;
    public string Body { get; set; } = string.Empty;
}

在 React JS 中,当用户注册到系统时,我使用 axios 发送电子邮件。

try {
        const response = await axios.post('https://localhost:7144/Auth/register', formData);
        console.log('Server Response:', response.data);
        if (response.status === 200) {
            const emailResponse = await axios.post('https://localhost:7144/api/Email', emaildata);
            console.log('Email Response:', emailResponse.data);
        }
    } catch (error) {
        console.error('Error:', error.response.data);
        if(error.response.data === "Email exist"){
            alert('Error: Email already exists and you can not register from existing email address');
        }
    }
reactjs asp.net asp.net-core-webapi html-email mailkit
1个回答
0
投票

我需要使用 ASP .NET Core 7 发送带有 HTML 标签的电子邮件 SMTP 和 MailKit。我已经发送了包含最少 html 标签的电子邮件 喜欢 。但我需要发送带有页眉和页脚的 图像(徽标)。

嗯,如果您可以分享您随电子邮件附件一起发送的 html,那就非常方便了。但你错过了。

但是,根据你的错误信息截图:

这表明您的 html 语法或发送该字符串的方式出现了问题。所以我认为,您应该首先在 html 可视化工具中进行测试,或者您必须检查 html 电子邮件正文中是否仍然存在任何错误。如果您的 CSS 属性或 html 标记中存在任何不正确的字符串或语法,您可能会遇到相同的错误,因此请仔细检查。

我的问题是我不知道如何在正文中插入 html 代码 其中包含 CSS 和图像。如何发送这样的电子邮件?

关于自定义 eamil 正文,例如 CSS 或图像,您可以在您可以定义的样式标签中使用带有必需属性的内联 css,但它必须位于同一位置。不应放置任何可能损坏的外部参考。另一方面,对于图像,您可以使用base64图像转换,就像我们在html中使用的方式

image src
。或者您可以直接使用位于 wwwroot 文件夹中的图像路径。不过base64更合适。

您可以执行以下操作:

var bodyBuilder = new BodyBuilder();
        bodyBuilder.HtmlBody = @"
            <html>
 <head>
    <style>
        /* Your CSS styles here */
    </style>
</head>
<body>
    <h1 style='color:red;'>Hello!</h1>
    <p>This is a sample HTML email with a base64-encoded image.</p>
    <img src="data:image/png;base64,iVBORw0KGgoA_Your_Base_64_Code_fv/X6F4MHQC0/0PyyAAAAAElFTkSuQmCC" alt="Base64 Encoded Logo">
</body>
</html>";

构建完上面的 html 字符串后,您可以在您的

email.Body

中传递/绑定它

输出:

当eamil发送出去时,应该如下所示:

注意:如果您需要其他帮助或示例,请参阅此官方文档。另外这个也可能有帮助

© www.soinside.com 2019 - 2024. All rights reserved.