发送生成的Pdf作为电子邮件附件Asp.NetCore [英] Send Generated Pdf as Email Attachment Asp.NetCore

查看:81
本文介绍了发送生成的Pdf作为电子邮件附件Asp.NetCore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rotativa将我的视图转换为pdf.我想将生成的pdf作为电子邮件附件发送(而不必先将其下载到磁盘上).我一直在遵循一堆教程来做到这一点,但是我一直在转圈.我将不胜感激.

I am using Rotativa to convert my view to pdf. I would like to send that generated pdf as an email attachment (without having to download it first to disk). I've been following a bunch of tutorials to do this but I just keep going round in circles. I would much appreciate any help I can get.

public async Task<IActionResult>SomeReport()
{
...
return new ViewAsPdf (report)
}
return view();


MemoryStream memoryStream = new MemoryStream();

MimeMessage msg = new MimeMessage();
MailboxAddress from = new MailboxAddress ("Name", "emailAddress")
msg.From.Add(from);
MailboxAddress to = new MailboxAddress ("Name", "emailAddress")
msg.From.Add(to);
BodyBuilder bd = new BodyBuilder();
bb.HtmlBody ="some text";
bb.Attachments.Add("attachmentName", new MemoryStream());
msg.Body = bb.ToMessageBody();
SmtpClient smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com",465, true);
smtp.Authenticate("emailAddress", "Pwd");
smtp.Send(msg);
smtp.Disconnect(true);
smtp.Dispose();

编辑

Parent View from which Email is sent

@Model MyProject.Models.EntityViewModel 
<a asp-action= "SendPdfMail" asp-controller ="Student" asp-route-id = "@Model.Student.StudentId">Email</a>
 ...


SendPdfMail action in Student Controller
public async Task<IActionResult> SendPdfMail(string id)
{  
  var student = await context.Student. Where(s => s.StudentId == id);
  if (student != null)
  {
   ...
   var viewAsPdf = new ViewAsPdf("MyPdfView", new{route = id})
  {      
           Model = new EntityViewModel(),
            FileName = PdfFileName,

        ...
    }
   }
    };

推荐答案

使用Rotativa.AspNetCore完整回答.代码是在VS 2019,Core 3.1,Rotativa.AspNetCore 1.1.1中开发的.

Complete answer using Rotativa.AspNetCore. Code is developed in VS 2019, Core 3.1, Rotativa.AspNetCore 1.1.1.

Nuget

Install-package Rotativa.AspNetCore

样品控制器

public class SendPdfController : ControllerBase
{
    private const string PdfFileName = "test.pdf";

    private readonly SmtpClient _smtpClient;

    public SendPdfController(SmtpClient smtpClient)
    {
        _smtpClient = smtpClient;
    }

    [HttpGet("SendPdfMail")] // https://localhost:5001/SendPdfMail
    public async Task<IActionResult> SendPdfMail()
    {
        using var mailMessage = new MailMessage();
        mailMessage.To.Add(new MailAddress("a@b.c"));
        mailMessage.From = new MailAddress("c@d.e");
        mailMessage.Subject = "mail subject here";

        var viewAsPdf = new ViewAsPdf("view name", <YOUR MODEL HERE>)
        {
            FileName = PdfFileName,
            PageSize = Size.A4,
            PageMargins = { Left = 1, Right = 1 }
        };
        var pdfBytes = await viewAsPdf.BuildFile(ControllerContext);

        using var attachment = new Attachment(new MemoryStream(pdfBytes), PdfFileName);
        mailMessage.Attachments.Add(attachment);

        _smtpClient.Send(mailMessage); // _smtpClient will be disposed by container

        return new OkResult();
    }
}

选项类

public class SmtpOptions
{
    public string Host { get; set; }
    public int Port { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
}

在Startup#ConfigureServices

In Startup#ConfigureServices

services.Configure<SmtpOptions>(Configuration.GetSection("Smtp"));

// SmtpClient is not thread-safe, hence transient
services.AddTransient(provider =>
{
    var smtpOptions = provider.GetService<IOptions<SmtpOptions>>().Value;
    return new SmtpClient(smtpOptions.Host, smtpOptions.Port)
    {
      // Credentials and EnableSsl here when required
    };
});

appsettings.json

appsettings.json

{
  "Smtp": {
    "Host": "SMTP HOST HERE",
    "Port": PORT NUMBER HERE,   
    "Username": "USERNAME HERE",
    "Password": "PASSWORD HERE"
  }
}

这篇关于发送生成的Pdf作为电子邮件附件Asp.NetCore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆