DoukeN
DoukeN

Reputation: 33

Send Form Data as PDF attachment through Sendgrid

I want to submit a form's data as a PDF attachment through Sendgrid.

The flow is as it follows:

  1. A customer fills a form on a webpage.

  2. Press a submit button.

  3. A PDF is generated through FDPF.

  4. An email is sent to me, through SendGrid, with some text and the generated PDF as an attachment.

Here is some of the code:

<?php

if(isset($_POST['sendemail']))
{
    
    require('fpdf/fpdf.php');
    $title = 'Inscrição';
    $name = $_POST['name'];
    $email_id = $_POST['email'];
    $age = $_POST['age'];
    $aulas = $_POST['aulas'];
    $experience = $_POST['experiencia-dança'];
    $conhecimento = $_POST['conhecimento'];
    $comentario = $_POST['comentario'];

(...)

    $pdf = new FPDF();
    $pdf -> AddPage();
    $pdf->SetTitle($title);

(...)

   $pdf->Output();

(...)

   $sendgrid = new \SendGrid($API_KEY);
   $email = new \SendGrid\Mail\Mail();
   $email->setFrom("********@gmail.com", "***** SAMA");
   $email->setSubject("Email de teste");
   $email->addTo("*****@gmail.com", "****SAMA");
   $email->addContent("text/plain", $comentario);

   If($sendgrid->send($email));
        {
            $msg = "Obrigado pelo seu contacto!";
        }

With this code, I can send the email, but no attachment is coming.

The problem is when I add the following lines of code, the email stop being sent to my inbox:

    $attachment = $pdf;
    $file_encoded = base64_encode(file_get_contents($attachment));
    $email->addAttachment(
    $file_encoded,
    "application/text",
    "test.pdf",
    "attachment"
    );  

Can somebody please help me with this?

Best regards

Upvotes: 1

Views: 488

Answers (1)

DoukeN
DoukeN

Reputation: 33

Resolved the problem with this lines of code:

$pdfdoc = $pdf->Output("pdf.pdf", "S");

$att1 = new \SendGrid\Mail\Attachment();
$att1->setContent($pdfdoc);
$att1->setType("application/octet-stream");
$att1->setFilename(basename("pdf.pdf"));
$att1->setDisposition("attachment");
$email->addAttachment($att1);

Upvotes: 1

Related Questions