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?
Related
I'm working on editing a site which has been built using some strange Smarty system, template TPL files and a load of JS and PHP.
I have a Classes in PHP files which sends and email to an array of email address from a differnt PHP file.
I'm wanted to add to this array so it sends a copy of the email to the person who filled in the form.
The array of recipents is:
//target email address settings
$this->settings['mailer_address_booknow'] = array('ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'james#bernhardmedia.com');
And the sending PHP file is:
public function SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message ) {
$smartyObj = Configurator::getInstance()->smarty;
$send_message = '';
$send_result = 0;
try {
$mail = new PHPMailer( true );
$mail->IsSMTP( true );
$mail->SMTPDebug = false;
$mail->IsHTML( true );
$mail->Host = Configurator::getInstance()->getSettings( "phpmailer_smtp" );
$mail->ClearAddresses();
for( $x = 0;$x < sizeof($email_address_array);$x++ ){
$mail->AddAddress( trim($email_address_array[$x]) );
}
$smartyObj->assign( 'email_data', $email_data );
$mail->SetFrom( 'info#forexchange.co.uk', 'Forexchange Currency Order');
$mail->Subject = $subject;
$mail->Body = $smartyObj->fetch( $template );
if(!$mail->Send()) {
} else {
$send_result = 1;
}
} catch (phpmailerException $e) {
$send_message = $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
$send_message = $e->getMessage(); //Boring error messages from anything else!
}
//echo $send_result;
//exit;
return $send_result;
}
The form is on the home page of this site - http://www.forexchange.co.uk/
Please help, I'm stumped!
Smarty I think refers to the Smarty template Engine for php see here
Append the email address to the array $email_address_array
When you call the method
SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message );
either append the email to that data set ($email_address_array) before you call it or append it inline ( in the call)
Can you show how you call it?
EDIT
If your data is stored in
$this->settings['mailer_address_booknow'];
add that to the call,
SendEmail( $this->settings['mailer_address_booknow'] , $email_data, $subject, $template, &$send_message );
if you need to add to that array then do this before calling it
$this->settings['mailer_address_booknow'] = "ADDED_EMAIL";
I am trying to send attachments with SendGrid through PHP, but keep getting a corrupted file error when I open the attachment. The error message "We're sorry. We can't open 'file.docx' because we found a problem with its contents" and when I click on the details of the error I see "The file is corrupt and cannot be opened"
My code looks like the below:
$sendGridLoginInfo = $contactViaEmail->getSendGridLoginInfo();
$sendgrid = new SendGrid($sendGridLoginInfo['Username'], $sendGridLoginInfo['Password']);
$mail = new SendGrid\Mail();
//Add the tracker args
$mail->addUniqueArgument("EmailID", $emailID);
$mail->addUniqueArgument("EmailGroupID", $emailGroupID);
/*
* INSERT THE SUBSITUTIONS FOR SEND GRID
*/
foreach ($availableSubstitutions as $availableSubstitution)
{
$mail->addSubstitution("[[" . $availableSubstitution . "]]", $substitutions[$availableSubstitution]);
}
/*
* ADD EACH EMAIL AS A NEW ADD TO
* This makes it BCC (because each person gets their own copy) and each person gets their own individualized email.
*/
foreach ($emailInfo['SendToEmailAddress'] as $toEmail)
{
if ($sendToLoggedInUser)
{
$mail->addTo($adminEmailAddress);
}
else
{
$mail->addTo($toEmail);
}
$trashCount++;
}
//Set the subject
$mail->setSubject($emailInfo['EmailSubject']);
//Instantiate the HTML Purifier (for removing the html)
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML', 'Allowed', '');
$purifier = new HTMLPurifier($config);
$mail->setText($purifier->purify($emailBody));
$mail->setHtml($emailBody);
if ($emailInfo['AttachmentID'])
{
$sql = "SELECT
AttachmentPath
FROM
EmailAttachments
WHERE
EmailAttachments.AttachmentID = :attachmentID";
if ($query = $pdoLink->prepare($sql))
{
$bindValues = array();
$bindValues[":attachmentID"] = $emailInfo['AttachmentID'];
if ($query->execute($bindValues))
{
if ($row = $query->fetch(\PDO::FETCH_ASSOC))
{
$attachment = "";
$mail->addAttachment($sitedb . $row['AttachmentPath']);
}
}
}
}
if ($sendToLoggedInUser)
{
$mail->setFrom($adminEmailAddress);
$mail->setReplyTo($adminEmailAddress);
}
else
{
$mail->setFrom($emailInfo['FromAddress']);
$mail->setReplyTo($emailInfo['ReplyTo']);
}
$mail->setFromName($emailInfo['FromName']);
$sendgrid->web->send($mail);
I've played with the content type and everything else that I can think of and just cannot find out what is causing the attachments to be corrupted.
You need to create an attachment object to add an attachment, you can't use the path directly like you are. SendGrid requires files to be sent as base64 encoded strings.
You'll need to create the attachment object, you could do this as a method:
public function getAttachment($path)
{
if (!file_exists($path)) {
return false;
}
$attachment = new SendGrid\Attachment;
$attachment->setContent(base64_encode(file_get_contents($path)));
$attachment->setType(mime_content_type($path));
$attachment->setFilename(basename($path));
$attachment->setDisposition('attachment');
return $attachment;
}
Then add it to your email:
$attachment = $this->getAttachment($sitedb . $row['AttachmentPath']);
if ($attachment instanceof SendGrid\Attachment) {
$mail->addAttachment($attachment);
}
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?
I'm trying to send mail for a contact form locally by swiftmailer and gmail. I've checked every line and I know the problem is 'setFrom' .
$app->post('/contact', function ($request, $response, $args){
$body = $this->request->getParsedBody();
$name = $body['name'];
$email = $body['email'];
$msg = $body['msg'];
if(!empty($name) && !empty($email) && !empty($msg) ){
$cleanName = filter_var($name,FILTER_SANITIZE_STRING);
$cleanEmail = filter_var($name,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($name,FILTER_SANITIZE_STRING);
}else {
//redirecting to contact page
}
//sending email
$transporter = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')
->setUsername('xxx#gmail.com')
->setPassword('xxx');
$mailer= \Swift_Mailer::newInstance($transporter);
$message = \Swift_Message::newInstance();
$message->setSubject('Email from our website');
$message->setTo(array('ns.falahian#gmail.com'));
$message->setBody($cleanMsg);
$message->setFrom([
$cleanEmail => $cleanName
]);
$result=$mailer->send($message);
if ($result > 0) {
$path = $this->get('router')->pathFor('home');
return $response->withRedirect($path);
} else {
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
}
});
as you can see I also use Slim 3 framework. when I run the code I get this error:
Slim Application Error
A website error has occurred. Sorry for the temporary inconvenience.
But if I replace the $cleanEmail with 'x#y.z' the code works!
what should I do?
I know that by using gmail I can't change the sender name but I want to upload this code in a webhost and I don't want to get this issue there.
And can anyone suggest a better way for redirecting in Slim 3? Instead of these two lines:
$path = $this->get('router')->pathFor('contact');
return $response->withRedirect($path);
I've set names for my routes like this:
$app->get('/contact', function ($req, $res, $args) {
return $this->view->render($res, "contact.twig");
})->setName('contact');
thanks a lot!
You probably want to do the following instead.
$cleanEmail = filter_var($email,FILTER_SANITIZE_EMAIL);
$cleanMsg = filter_var($msg,FILTER_SANITIZE_STRING);
Here is my code for attaching docs in mails. I am using YiiMail extension for that.
controller-
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
$message = new YiiMailMessage;
$message->Body=$_POST['ContactForm']['body'];
$message->subject = $_POST['ContactForm']['subject'];
$message->addTo($_POST['ContactForm']['email']);
$message->from = "from#gmail.com";
//Adding attachment
//$uploadedFile = CUploadedFile::getInstanceByName('file'); // get the CUploadedFile
// $uploadedFileName = $uploadedFile->tempName;
$model->file=CUploadedFile::getInstance($model,'file');
$uploadedFileName =$model->file->tempName; // will be something like 'myfile.jpg'
$swiftAttachment = Swift_Attachment::fromPath($uploadedFileName); // create a Swift Attachment from the temporary file
$message->attach($swiftAttachment); // now attach the correct type
Yii::app()->mail->send($message);
}
$this->render('contact',array('model'=>$model));
}
I am able to send mails with attachments, but no attachment is found in mail. It says "no preview is available". Where am I going wrong here?