Generate PDF and attach to send email c#

Asked

Viewed 145 times

0

Good afternoon guys, I have a modal, where the user can send an email, in this modal, I loaded a HTML, so that I can generate the PDF and attach to send in the email. But I’ve seen several articles on the Internet, and I’m even a little confused, in which line of reasoning should I follow.

Follow in the API how the email is sent:

 [HttpPut]
    [Route("sendEmail")]
    [Authorize(AuthenticationSchemes = "Bearer", Policy = WriteBudgetPolicy.Name)]
    public async Task<IActionResult> SendEmail(EmailProposalsViewModel obj)
    {
        var company = _companyAppService.GetUnique(obj.CompanyId);
        var result = new ReturnViewModel { Model = company };
        try
        {

            await Util.SendEmailProposalsAsync(obj.Email, company.Email, company.Password, company.Port.Value, company.Server, obj.Message, obj.Subject, company.Name);
        }
        catch (Exception ex)
        {
            result.Errors = new Error { Key = "SendEmail", Value = ex.Message };
        }
        return ApplicationResult(result);
    }


  public static Task SendEmailProposalsAsync(string destinatario, string remetente, string password, int port, string host, string message, string subject, string displayName)
    {

        var msg = new MailMessage
        {
            From = new MailAddress(remetente, displayName),
            To = { destinatario },
            Subject = subject,
            Body = message,
            IsBodyHtml = true,
        };

        var smtpCliente = new SmtpClient(host, port);
        smtpCliente.UseDefaultCredentials = false;
        var credentials = new NetworkCredential(remetente, password);
        smtpCliente.Credentials = credentials;
        smtpCliente.EnableSsl = false;
        if (host == "gmail.com")
        {
            smtpCliente.Host = "smtp.gmail.com";
            smtpCliente.EnableSsl = true;
        }

        if (host == "yahoo.com.br")
        {
            smtpCliente.Host = "smtp.mail.yahoo.br";
        }

        if (host == "hotmail.com")
        {
            smtpCliente.Host = "smtp.live.com";
            smtpCliente.EnableSsl = true;
        }

        if (host == "live.com")
        {
            smtpCliente.Host = "smtp.live.com";
            smtpCliente.EnableSsl = true;
        }

        smtpCliente.Send(msg);

        return Task.FromResult(0);
    }

The front-end is in angular, it would be possible to generate the PDF and send by email, without needing to save(that would be ideal)? Utilizdo .net core

  • You can generate it in the front end and post to the backend and send, generate and send in the backend, have a template and change the values before sending... There are several different approaches and depend a lot on your scenario and need.

  • @Leandroangelo my need, would take advantage of the front, because I already have a whole HTML ready, just wanted to generate it in PDF in case, if it was possible to only save temporarily, and then send as an attachment in the email.

1 answer

1


The front end is a presentation layer. As the name says, it should be used (only) for presentation. Since nothing that comes from the front end is reliable, however much you have any logic in it should be repeated/validated in the backend.

Transposing to your case, a "simple" PDF to be attached in an email, if done at the front end, is subject to changes by the user.

Given this short preface, it DOES NOT generate your pdf on the front end. It could even be "emulated" to have a more elegant presentation for its users, however, it should be generated, even in memory, in the back-end.

Is it possible to generate a PDF with . net core? Yes, playing fast on google you should find a dozen options, paid, free, open source, to taste. Searching for "PDF" in nuget.org you will find more than 2,000 results.

Regarding the code presented...

For a share SendEmail, it does not seem reasonable to use the verb PUT. The POST would be more widely applied in this case.

Although it is a somewhat controversial task, try to give names with some meaning to their variables. obj is not very suggestive to know what it is.

Sending an email "inside" an http request is questionable. Sending an email can be time consuming and should be done in the background. Depending on the case, to avoid excessive complexity, "one can" send the request in the middle.

Regardless of whether or not to send the email in a "synchronous" way, it should not "ever" be done in a controller. A service layer should be responsible for this.

Finally, e-mail should be sent via a transactional email service. Many of the "traditional" providers like gmail are blocking the use of smtp with user and password. Where permitted, even, specific "passwords" are used for this use. Alternatively, Oauth should be used.

  • Thanks @tvdias, in case it is not in the controller, it was separated, but at the time of inserting the question was all together. And for variable obj I’m still running the tests, so I just wanted to make sure the parameters are being passed correctly. Regarding the PDF, I need something really user friendly, I’m still looking to generate by own front, since I already have the template ready PDF.

  • @Mariana, if you have the PDF template, load and fill in the template in the backend. Otherwise, the system will always be more likely to be exploited at the frontend.

  • Being "friendly" or not is independent of the PDF being or not generated in the frontend.

  • Oh yes, I love him in a div, with all the necessary filling, do you have any way to tell me to generate it in the API ? I don’t necessarily need to save, I need to send it by email, it can be saved in memory, something like!!

  • This is what I’m thinking, the front, generates me the html file, all right!! @tvdias, ai estou procurando uma forma de passar para a API

  • Still, if the front generates HTML it can be changed by calling the backend.

  • on the front I have the whole configuration, where I already apply the CSS, I can’t take advantage of it ?

  • You can, it will always depend on what you have and how you do it, but in general you do not send "a page" by email and even if it is necessary, you can put your backend to make the request to the site, recovering the HTML of this request

  • I do not want to send the page by email, I would like to take this page, generate its pdf, and then yes send by email.

  • and pq not in the backend? where would be more difficult to be explored?

  • It’s okay to be back-end, but which tool should I follow for this ?

  • https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.getasync?view=net-5.0

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.