В моем приложении электронной коммерции (Blazor Server, Blazor WASM и ASP.NET Core API) я отправляю клиенту электронное письмо с подтверждением заказа от API. Для этого письма я использую HTML-шаблон. Мне не удалось отобразить логотип и изображения заказанного товара в электронном письме.Вот HTML-шаблон:
private async Task SendOrderConfirmationEmail(OrderHeaderDTO orderHeaderDTO)
{
try
{
// Get the order for details in the template
var orders = await _orderRepository.GetOrdersByUser(orderHeaderDTO.UserId);
var order = orders.Where(o => o.OrderHeader.Id == orderHeaderDTO.Id).FirstOrDefault();
// Construct the path to the file
var pathToFile = Path.Combine("Templates", "EmailTemplate", "Confirmation_EmailTemplate.html");
// Check if the file exists
if (!System.IO.File.Exists(pathToFile))
{
throw new FileNotFoundException("The email template file was not found.", pathToFile);
}
var builder = new BodyBuilder();
using (var SourceReader = System.IO.File.OpenText(pathToFile))
{
builder.HtmlBody = SourceReader.ReadToEnd();
}
var tableRows = new StringBuilder();
foreach (var detail in order.OrderDetails)
{
var imageUrl = $"http://localhost:7253/{detail.Product?.ImageUrls.FirstOrDefault()}";
tableRows.Append($@"
[img]{imageUrl}[/img]
{detail.ProductName}
Quantity: {detail.Count}
Color: {detail.Product?.Color}
{detail.Price.ToString("C", CultureInfo.InvariantCulture)} Per Unit
Size: {detail.Size}
{(detail.Price * detail.Count).ToString("C", CultureInfo.InvariantCulture)}[/b] Total
");
}
// Replace the placeholder in the HTML template with the generated tableRows
builder.HtmlBody = builder.HtmlBody.Replace("", tableRows.ToString());
builder.HtmlBody = builder.HtmlBody.Replace("--OrderId--", orderHeaderDTO.Id.ToString());
builder.HtmlBody = builder.HtmlBody.Replace("--OrderDate--", orderHeaderDTO.OrderDate.ToString());
builder.HtmlBody = builder.HtmlBody.Replace("--Name--", orderHeaderDTO.Name);
builder.HtmlBody = builder.HtmlBody.Replace("--Address--", orderHeaderDTO.StreetAddress);
builder.HtmlBody = builder.HtmlBody.Replace("--City--", orderHeaderDTO.City);
builder.HtmlBody = builder.HtmlBody.Replace("--SubTotal--", orderHeaderDTO.OrderTotal.ToString("C", CultureInfo.InvariantCulture));
builder.HtmlBody = builder.HtmlBody.Replace("--Total--", (orderHeaderDTO.OrderTotal
+ 5).ToString("C", CultureInfo.InvariantCulture));
// Add the logo to the email
var logoPath = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot", "images", "Logo.png");
var logo = builder.LinkedResources.Add(logoPath.Replace("API", "Server"));
logo.ContentId = MimeUtils.GenerateMessageId();
builder.HtmlBody = builder.HtmlBody.Replace("--Logo--", string.Format(@"
[img]cid:{0}[/img]
", logo.ContentId));
// Send the email
await _emailSender.SendEmailAsync(orderHeaderDTO.Email, "Order Confirmation", builder.HtmlBody);
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
В моем приложении электронной коммерции (Blazor Server, Blazor WASM и ASP.NET Core API) я отправляю клиенту электронное письмо с подтверждением заказа от API. Для этого письма я использую HTML-шаблон. Мне не удалось отобразить логотип и изображения заказанного товара в электронном письме.[b]Вот HTML-шаблон: [code]
[/code] Вот метод электронной почты. Поскольку я пытаюсь отправить электронное письмо через API, мне пришлось изменить путь к изображению. [code]private async Task SendOrderConfirmationEmail(OrderHeaderDTO orderHeaderDTO) { try { // Get the order for details in the template var orders = await _orderRepository.GetOrdersByUser(orderHeaderDTO.UserId); var order = orders.Where(o => o.OrderHeader.Id == orderHeaderDTO.Id).FirstOrDefault();
// Construct the path to the file var pathToFile = Path.Combine("Templates", "EmailTemplate", "Confirmation_EmailTemplate.html");
// Check if the file exists if (!System.IO.File.Exists(pathToFile)) { throw new FileNotFoundException("The email template file was not found.", pathToFile); } var builder = new BodyBuilder(); using (var SourceReader = System.IO.File.OpenText(pathToFile)) { builder.HtmlBody = SourceReader.ReadToEnd(); }
var tableRows = new StringBuilder(); foreach (var detail in order.OrderDetails) { var imageUrl = $"http://localhost:7253/{detail.Product?.ImageUrls.FirstOrDefault()}"; tableRows.Append($@"
[img]{imageUrl}[/img]
{detail.ProductName}
Quantity: {detail.Count}
Color: {detail.Product?.Color}
{detail.Price.ToString("C", CultureInfo.InvariantCulture)} Per Unit
Size: {detail.Size}
{(detail.Price * detail.Count).ToString("C", CultureInfo.InvariantCulture)}[/b] Total
"); }
// Replace the placeholder in the HTML template with the generated tableRows builder.HtmlBody = builder.HtmlBody.Replace("", tableRows.ToString()); builder.HtmlBody = builder.HtmlBody.Replace("--OrderId--", orderHeaderDTO.Id.ToString()); builder.HtmlBody = builder.HtmlBody.Replace("--OrderDate--", orderHeaderDTO.OrderDate.ToString()); builder.HtmlBody = builder.HtmlBody.Replace("--Name--", orderHeaderDTO.Name); builder.HtmlBody = builder.HtmlBody.Replace("--Address--", orderHeaderDTO.StreetAddress); builder.HtmlBody = builder.HtmlBody.Replace("--City--", orderHeaderDTO.City); builder.HtmlBody = builder.HtmlBody.Replace("--SubTotal--", orderHeaderDTO.OrderTotal.ToString("C", CultureInfo.InvariantCulture)); builder.HtmlBody = builder.HtmlBody.Replace("--Total--", (orderHeaderDTO.OrderTotal + 5).ToString("C", CultureInfo.InvariantCulture)); // Add the logo to the email var logoPath = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot", "images", "Logo.png"); var logo = builder.LinkedResources.Add(logoPath.Replace("API", "Server")); logo.ContentId = MimeUtils.GenerateMessageId(); builder.HtmlBody = builder.HtmlBody.Replace("--Logo--", string.Format(@" [img]cid:{0}[/img] ", logo.ContentId));
// Send the email await _emailSender.SendEmailAsync(orderHeaderDTO.Email, "Order Confirmation", builder.HtmlBody); } catch (Exception e) { throw new Exception(e.Message); } } [/code] Вот как я отправляю: [code]public async Task SendEmailAsync(string email, string subject, string htmlMessage) { try { var emailToSend = new MimeMessage(); emailToSend.From.Add(MailboxAddress.Parse("test@test.com")); emailToSend.To.Add(MailboxAddress.Parse(email)); emailToSend.Subject = subject; emailToSend.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = htmlMessage };
// Send email using var emailClient = new SmtpClient(); await emailClient.ConnectAsync("smtp.gmail.com", 587, MailKit.Security.SecureSocketOptions.StartTls); await emailClient.AuthenticateAsync("test@test.com", "test"); await emailClient.SendAsync(emailToSend); await emailClient.DisconnectAsync(true); } catch (Exception) { throw; } } [/code] Ошибок нет, но и изображения в электронном письме тоже нет. Я также пытался использовать URL-адрес изображения ([code]http://localhost:7253/images/Logo.png[/code]), но он не отобразился.