I want to submit a form's data as a PDF attachment through Sendgrid.
The flow is as it follows:
A customer fills a form on a webpage.
Press a submit button.
A PDF is generated through FDPF.
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
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);
Related
In Sales > Invoices when Send Email is clicked, I need a PDF to be attached to the email. I'm using Magento 2.3.3.
$pdf = 'path to pdf';
$this->configureEmailTemplate();
$this->transportBuilder->addTo(
$this->identityContainer->getCustomerEmail(),
$this->identityContainer->getCustomerName()
);
$copyTo = $this->identityContainer->getEmailCopyTo();
if (!empty($copyTo) && $this->identityContainer->getCopyMethod() == 'bcc') {
foreach ($copyTo as $email) {
$this->transportBuilder->addBcc($email);
}
}
//$transport = $this->addAttachment($pdf, $pdfFileName);
$transport = $this->transportBuilder->addAttachment($pdf, 'test');
$transport = $this->transportBuilder->getTransport();
$transport->sendMessage();`
I tried to write addAttachemtment function to the customized transportBuilder page. But it didn't work.
Does anyone know how to do this?
I have a google apps scripts app that gets Gmail message attachments, posts it to DB using JDBC. then on the server, a PHP script gets the data and puts in into a file and attaches it to an email.
the problem is that the files are corrupt when email arrives
here is the google apps script function that gets the attachment content
function getMessageAttachmentsArray(msg){
var GmailAttachments = msg.GmailMessage.getAttachments();
var validAttachments = [];
var attachmentNames = [];
if(GmailAttachments)
{
for(i in GmailAttachments)
{
var gName = GmailAttachments[i].getName();
attachmentNames.push(gName);
var mimeType = GmailAttachments[i].getContentType();
var size = GmailAttachments[i].getSize();
var content = Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
var push = {"content":content,"mimeType":mimeType,"fileName":gName,"size":size,"id":""};
validAttachments.push(push);
}
}
return [validAttachments, attachmentNames];
}
here is the PHP code that generated the email from the file data:
require_once 'smtpmail/classes/class.phpmailer.php';
$mail = new PHPmailer(true);
$email = $argv[1];
$messageid = $argv[2];
$fax_number = $argv[3];
$attachments = array();
//get the attachments for this email
$Sql = "select * from user_attachments where email = '$email' and messageid like '$messageid%'";
$res = mysql_query($Sql);
while($row = mysql_fetch_array($res)){
$return['filename'] = $row['name'];
$return['mime'] = $row['mime_type'];
$content = base64_decode(str_pad(strtr($row['raw_data'], '-_', '+/'), strlen($row['raw_data']) % 4, '=', STR_PAD_RIGHT));
$temp_file = tempnam(sys_get_temp_dir(), 'Fax');
file_put_contents($temp_file, $content);
$return['file'] = $temp_file;
array_push($attachments, $return);
}
try{
$mail->IsSMTP();
$mail->SMTPDebug = 1;
$mail->SetFrom("example#example.com", "example email");
$mail->Subject = '';
$mail->Body = ' '; //put in a blank body to avoid smtp error
$mail->AddAddress($email);
foreach($attachments as $file){
$mail->AddAttachment($file['file'], $file['filename'], 'base64' ,mime_content_type($file['file']));
}
if($mail->send()){
echo "email to $email sent successfully\n";
}else{
echo "error sending email to $email\n";
}
}catch(phpmailerException $e){
echo $e->errorMessage();
}catch(Exception $e){
echo $e->getMessage();
}
When the message is received it shows the attachments but when downloaded I can not open them and there is a message that the file is corrupt or the file extension does not match the file format
what am I doing wrong?
Thanks in advance.
EDIT:
I tried emailing the attachment without posting to the DB, by posting to the server with UrlFetchApp() and the results are the same. clearly, I am doing something wrong with Base64_encode / decode...
maybe the google apps scripts :
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
creates a different base64 format than PHP base64_decode expects?
p.s.
I tried also with and without 'str_pad' and I still got the same results.
I changed:
Utilities.base64Encode(GmailAttachments[i].getDataAsString(), Utilities.Charset.UTF_8);
to:
Utilities.base64Encode(GmailAttachments[i].getBytes());
and it works
private function mailToClient($file, $customer, $trans_id = "")
{
if(!$customer["email"]) return;
$mail = &$this->getMailObject();
$country = $_SESSION[PROJECT]["user"]["details"]["country"];
$lang = getLanguage();
if( empty($trans_id))
{
//get header
$set = getContentByCode("client_email_header");
if(!$set->EOF)
$msg_html = $set->fields["content_$lang"];
}
else
{
//get header
$set = getContentByCode("client_email_with_card_header");
if(!$set->EOF)
$msg_html = $set->fields["content_$lang"];
}
if( $country != "Schweiz" && !empty($trans_id))
{
//get header
$set = getContentByCode("client_email_nonswiss_card");
if(!$set->EOF)
$msg_html = $set->fields["content_$lang"];
}
$msg_html = $this->replacePlaceHolders($msg_html, $customer);
$msg_plain = strip_tags($msg_html);
//get footer
$set = getContentByCode("client_email_footer");
if(!$set->EOF)
$msg_html2 = $set->fields["content_$lang"];
$msg_html2 = $this->replacePlaceHolders($msg_html2, $customer);
$msg_plain2 = strip_tags($msg_html2);
//get order
$order = file_get_contents($file);
$mail->Subject = (EMAIL_SUBJECT_PREFIX ? EMAIL_SUBJECT_PREFIX." " : "")."Order from TERRA KERAMIK";
$mail->Body = $msg_html."<br />".$order."<br />".$msg_html2;
$mail->AltBody = $msg_plain.$msg_plain2;
//$mail->AddAttachment($file, date("d.m.Y H_i")." order.xls");
$mail->AddAttachment($file, date("d.m.Y H_i")." ".mn_transliterate($customer["name"]." ".$customer["surname"].".pdf", $encoding = 'base64', $type = 'application/pdf'));
$mail->AddAddress($customer["email"], $customer["name"]." ".$customer["surname"]);
$mail->Send();
I know there are similar questions, however the solutions they are offering don't help. Just trying my luck.
So, I've got this code which send a client an email plus adds an attachment. The attachment itself is a html table. It is also added into the email and looks like this
When I receive an email the attachment is there but is corrupted or damaged. Other solutions advised to add "$encoding = 'base64', $type = 'application/pdf'" along with file path and name.
This doesn't change situation at all. At the same time this code, which is currently commented
//$mail->AddAttachment($file, date("d.m.Y H_i")." order.xls"); works pretty fine, I do receive an excel file with information.
Any thoughts?
This is my code to send emails in SugarCRM CE 6.5.x version,
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid EntryPoint');
require_once('include/SugarPHPMailer.php');
$msg = new SugarPHPMailer();
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
//Setup template
require_once('XTemplate/xtpl.php');
$xtpl = new XTemplate('custom/modules/Users/ChangePassword.html');
//assign recipients email and name
$rcpt_email = 'sohan.tirpude#mphasis.com';
$rcpt_name = 'Sohan';
//Set RECIPIENT's address
$email = $msg->AddAddress($rcpt_email, $rcpt_name);
//Send msg to users
$template_name = 'User';
//Assign values to variables in template
$xtpl->assign('EMAIL_NAME', $rcpt_name);
$xtpl->parse();
//$body = "Hello Sohan, It's been 80 days that you haven't changed your password. Please take some time out to change password first before it expires.";
$msg->From = $defaults['email'];
$msg->FromName = $defaults['name'];
$msg->Body = from_html(trim($xtpl->text($template_name)));
//$msg->Body = $body;
$msg->Subject = 'Change Password Request';
$msg->prepForOutbound();
$msg->AddAddress($email);
$msg->setMailerForSystem();
//Send the message, log if error occurs
if (!$msg->Send()){
$GLOBALS['log']->fatal('Error sending e-mail: ' . $msg->ErrorInfo);
}
?>
Now this script send blanks emails, and when I hardcoded body part then it is takes those message written in body, and sends an email. So, please help me here.
I am trying to modify a script to send a email with an attachment. It works right now but all the fields are required and I was wondering what I am missing to make it so the fields are not required.
<?php
if (($_POST)) {
$success = $error = false;
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
$dir = dirname(__FILE__);
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport());
$message = Swift_Message::newInstance()
->setSubject('Imperial Order') // Message subject
->setTo(array($post->email => $post->name, 'ehilse#paifashion.com' => 'Janet McCauley')) // Array of people to send to
->setFrom(array('noreply#paifashion.com' => 'Imperial Order'))
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::fromPath($_FILES['attachment']['tmp_name'])->setFilename($_FILES['attachment']['name']));
// Send the email, and show user message
if ($mailer->send($message))
$success = true;
else
$error = true;
}
?>
I believe it has something to do with the foreach but if I try taking it out it breaks the whole code. If anyone can help that would be great. The reason I am taking out the validation is because i'm wanting to do it on the client side instead of server side.
you can remove the for each but then you'll have to request each posted field individually and process/validate them one at a time instead of in a loop as the loop is pulling all the post vars to local vars.
Also you don't need to require the swift mailer includes etc inside of the loop they can be moved outside of the loop as can the $mailer = new transport start line that can all go outside of the loop
EDIT WITH EXAMPLE
if (isset($_POST)) { //BAD BAD BAD way of checking there's better ways
$success = $error = false;
$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$input3 = $_POST['input3'];
$input4 = $_POST['input4'];
$dir = dirname(__FILE__);
// THIS BIT IS RETARDED BUT LEAVING IT IN FOR NOW
ob_start();
require_once($dir.'/html.php');
$html_message = ob_get_contents();
ob_end_clean();
// END RETARDED BIT
require_once($dir.'/swift/swift_required.php');
$mailer = new Swift_Mailer(new Swift_MailTransport());
if (isset($_FILES) && strlen($_FILES['attachment']['name']) > 0) { //here we're checking that there is attachments if there are then we're going to do the attach sw code
$message = Swift_Message::newInstance()
->setSubject('Imperial Order') // Message subject
->setTo(array($input1 => $input2, 'ehilse#paifashion.com' => 'Janet McCauley')) // Array of people to send to
->setFrom(array('noreply#paifashion.com' => 'Imperial Order'))
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
->attach(Swift_Attachment::fromPath($_FILES['attachment']['tmp_name'])->setFilename($_FILES['attachment']['name']));
} else {
//non attach sw code
$message = Swift_Message::newInstance()
->setSubject('Imperial Order') // Message subject
->setTo(array($input1 => $input2, 'ehilse#paifashion.com' => 'Janet McCauley')) // Array of people to send to
->setFrom(array('noreply#paifashion.com' => 'Imperial Order'))
->setBody($html_message, 'text/html') // Attach that HTML message from earlier
}
//there's better ways of doing the above but as an example this will suffice.
// Send the email, and show user message
if ($mailer->send($message)) {
$success = true;
} else {
$error = true;
}
}
?>