I am trying to create a PDF file using FPDF and send it via e-mail using PHPMailer. It did send the file, but for some reasons I cannot open the file, either from my email or using Adobe Reader (which gives me something like the file is damaged).
This is my code
require('fpdf.php');
require 'PHPMailerAutoload.php';
header("Access-Control-Allow-Origin: *");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','UB',28);
$pdf->Cell(0,10,"My Profile",0,1,'C');
$pdf->Ln();
$mail = new PHPMailer();
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;
// a random hash will be necessary to send mixed content
$separator = md5(time());
// carriage return type (we use a PHP end of line constant)
$eol = PHP_EOL;
// main header
$headers = "From: ".$from.$eol;
$headers .= "MIME-Version: 1.0".$eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
// no more headers after this, we start the body! //
$body = "--".$separator.$eol;
$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
$body .= "This is a MIME encoded message.".$eol;
// message
$body .= "--".$separator.$eol;
$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
$body .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$body .= $message.$eol;
// attachment
$body .= "--".$separator.$eol;
$body .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol;
$body .= "Content-Transfer-Encoding: base64".$eol;
$body .= "Content-Disposition: attachment".$eol.$eol;
$body .= $attachment.$eol;
$body .= "--".$separator."--";
$pdfdoc = $pdf->Output('','S');
$attachment = chunk_split(base64_encode($pdfdoc));
//Set who the message is to be sent from
$mail->setFrom('example#gmail.com', 'Baby Diary');
//Set who the message is to be sent to
$mail->addAddress('example2#gmail.com', 'haha');
//Set the subject line
$mail->Subject = 'PHPMailer mail() test';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AddStringAttachment($attachment, 'doc.pdf', 'base64', 'application/pdf');
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
It does give me output when I use $pdf->Output(), which hints to me that the problem should not be in FPDF side. Any suggestion will be much appreciated.
Your problem is with phpmailer and not with fpdf. Try using the standard PHPMailer class methods.
If I was you I'd try to rework your code from the attachement example included in the PHPMailer doc samples. And particularly I'd stick to using the PHPMailer methods rather that doing my own smtp formating.
So first save your pdf to file, and then try attaching the file with $mail->addAttachment() . And let PHPMailer handle the formating of the mail.
So you might end up with something like this code below (I haven't run it, you'll probably need to fine tune it) :
require('fpdf.php');
require 'PHPMailerAutoload.php';
header("Access-Control-Allow-Origin: *");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','UB',28);
$pdf->Cell(0,10,"My Profile",0,1,'C');
$pdf->Ln();
$pdfoutputfile = '/some-tmp-dir/temp-file.pdf';
$pdfdoc = $pdf->Output($pdfoutputfile, 'F');
// We're done with the pdf generation
// now onto the email generation
$mail = new PHPMailer();
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587;
$separator = md5(time()); // a random hash will be necessary to send mixed content
//Set who the message is to be sent from
$mail->setFrom('example#gmail.com', 'From Test address');
//Set who the message is to be sent to
$mail->addAddress('example2#gmail.com', 'to test address');
//Set the subject line
$mail->Subject = 'Test message with attachement';
$mail->Body = 'Test message with attached files.';
$mail->AddAttachment($pdfoutputfile, 'my-doc.pdf');
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
Related
I designed my website and hosted on my amazon ec2 instance and I bought my domain in godaddy (www.mydomain.com).Now I want a mail configuration in my contact form page in website.. Below its my code , I don't know where am I mistake the code?
<?php
if(isset($_REQUEST['submit'])) {
try {
$name = $_POST['name'];
echo "<script type='text/javascript'>alert('$name')</script>";
$email = $_POST['email'];
echo "<script type='text/javascript'>alert('$email')</script>";
$subject = $_POST['subject'];
echo "<script type='text/javascript'>alert('$subject')</script>";
$message = $_POST['message'];
echo "<script type='text/javascript'>alert('$message')</script>";
$response ="";
$body ="<div style='font-size:18px'>
<b>Name</b> : $name <br />
<b>Email address</b> : $email <br />
<b>Message</b> : $message <br />
</div>"
$to = "XXXXX#gmail.com";
require_once($_SERVER['DOCUMENT_ROOT'].'/samplemail/lib/class.phpmailer.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/samplemail/lib/class.smtp.php');
$mail = new PHPMailer(true);
//$mail->Host = "relay-hosting.secureserver.net"; // your SMTP Server
// echo $res;
$mail->IsSMTP();
$mail->Host = "email-smtp.us-east-1.amazonaws.com";
$mail->SMTPDebug = true;
$mail->SMTPAuth = true; // Auth Type
$mail->Port = 25;
$mail->IsSendmail();
//$mail->SMTPSecure = "ssl";
$mail->Username = "support#mydomain.com";
$mail->Password = "******";
$mail->Sender = "supportexample#mydomain.com";
$mail->From = "supportexample#mydomain.com";
$mail->AddReplyTo($email);
$mail->FromName = "Example";
$mail->AddAddress($to);
//$mail->AddAddress("desired recipient no.2 optional");
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->WordWrap = 50;
If($mail->Send()){
echo "<script type='text/javascript'>alert('Mail Send Successfully')</script>";
}
} catch (phpmailerException $e) {
echo "<script type='text/javascript'>alert('Failed')</script>";
echo $e->errorMessage();
}
}
?>
I got this error. How do solve this issue?
Could not execute: /var/qmail/bin/sendmail
You can't call random functions and expect it to all work magically.
You're setting up for SMTP with isSMTP(), but then ignoring all that by calling isSendmail(), when it looks like your server simply isn't set up for it. Why do that? Re-enable isSMTP and configure your script for your mail server correctly.
You're also requesting auth while disabling encryption; that's likely to fail on any modern server.
You're also using an old version of PHPMailer, and you've based your code on an obsolete example. Get the latest, and base your code on the examples provided.
I want to send mail using phpmailer from localhost XAMPP using SMTP server (gmail). But I keep getting this error:
Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
I tried many solutions regarding uncomment openSSL in php.ini file, changing the port 465("ssl") and 587("tls"), but it does not work.
My codes:
<?php
date_default_timezone_set('Etc/UTC');
'PHPMailerAutoLoad.php';
class.phpmailer.php if not already loaded
$port =465;
$securetype = 'ssl';
$from = 'myemail#gmail.com';
$name = 'User';
$toemail= "mymail#gmail.com";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->isSMTPDebug = 1;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'myemail#gmail.com';
$mail->Password = 'password';
$mail->SMTPSecure = $securetype;
$mail->Port = $port;
$mail->From = $from;
$mail->FromName = $name;
$mail->addAddress($toemail);
$mail->isHTML(true);
$mail->Subject = 'Test Mail Subject!';
$mail->Body = 'This is SMTP Email Test';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
?>
You will need class.phpmailer.php. If you're using SMTP, you'll need class.smtp.php.
Try this demo code:
<?php
require 'class.phpmailer.php';
require 'class.smtp.php';
//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
#require '../PHPMailerAutoload.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
//Set the hostname of the mail server
$mail->Host = 'mail.domain.com';
// use
// $mail->Host = gethostbyname('smtp.gmail.com');
// if your network does not support SMTP over IPv6
//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 25;
//Set the encryption system to use - ssl (deprecated) or tls
//$mail->SMTPSecure = 'tls';
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "demo#domain.com";
//Password to use for SMTP authentication
$mail->Password = "password";
//Set who the message is to be sent from
$mail->setFrom('demo#domain.com', 'subillion');
//Set an alternative reply-to address
#$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress("example#gmail.com");
//Set the subject line
$mail->Subject = 'Demo !!';
//Read an HTML message body from an external file, convert referenced images to embedded,
$mail->isHTML(true);
$msgbody = "This is a demo test !";
$mail->Body = $msgbody;
//send the message, check for errors
if (!$mail->send()) {
// echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
I'm sending a calendar invite via email but I want it automatically be accepted.
Is there something I can change in my code? My code looks like this:
function sendIcalEmail ($firstname, $lastname, $email, $meeting_date, $meeting_name, $meeting_duration) {
$from_name = “My Name”;
$from_address = “myname#mydomain.com”;
$subject = “Meeting Booking”; //Doubles as email subject and meeting subject in calendar
$meeting_description = “Here is a brief description of my meeting\n\n”;
$meeting_location = “My Office”; //Where will your meeting take place
//Convert MYSQL datetime and construct iCal start, end and issue dates
$meetingstamp = strtotime($meeting_date . ” UTC”);
$dtstart= gmdate(”Ymd\THis\Z”,$meetingstamp);
$dtend= gmdate(”Ymd\THis\Z”,$meetingstamp+$meeting_duration);
$todaystamp = gmdate(”Ymd\THis\Z”);
//Create unique identifier
$cal_uid = date(’Ymd’).’T’.date(’His’).”-”.rand().”#mydomain.com”;
//Create Mime Boundry
$mime_boundary = “—-Meeting Booking—-”.md5(time());
//Create Email Headers
$headers = “From: “.$from_name.” <”.$from_address.”>\n”;
$headers .= “Reply-To: “.$from_name.” <”.$from_address.”>\n”;
$headers .= “MIME-Version: 1.0\n”;
$headers .= “Content-Type: multipart/alternative; boundary=\”$mime_boundary\”\n”;
$headers .= “Content-class: urn:content-classes:calendarmessage\n”;
//Create Email Body (HTML)
$message .= “–$mime_boundary\n”;
$message .= “Content-Type: text/html; charset=UTF-8\n”;
$message .= “Content-Transfer-Encoding: 8bit\n\n”;
$message .= “<html>\n”;
$message .= “<body>\n”;
$message .= ‘<p>Dear ‘.$firstname.’ ‘.$lastname.’,</p>’;
$message .= ‘<p>Here is my HTML Email / Used for Meeting Description</p>’;
$message .= “</body>\n”;
$message .= “</html>\n”;
$message .= “–$mime_boundary\n”;
//Create ICAL Content (Google rfc 2445 for details and examples of usage, beware of adding tabs)
$ical = ‘BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN
VERSION:2.0
METHOD:PUBLISH
BEGIN:VEVENT
ORGANIZER:MAILTO:’.$from_address.’
DTSTART:’.$dtstart.’
DTEND:’.$dtend.’
LOCATION:’.$meeting_location.’
TRANSP:OPAQUE
SEQUENCE:0
UID:’.$cal_uid.’
DTSTAMP:’.$todaystamp.’
DESCRIPTION:’.$meeting_description.’
SUMMARY:’.$subject.’
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR’;
$message .= 'Content-Type: text/calendar;name="meeting.ics";method=REQUEST;charset=utf-8\n';
$message .= 'Content-Transfer-Encoding: 8bit\n\n';
$message .= $ical;
//SEND MAIL
$mail_sent = #mail( $email, $subject, $message, $headers );
if($mail_sent) {
return true;
} else {
return false;
}
}
Imho it is not or should not be possible to post an invite that automatically will be accepted. Instead you should inform your users that they can they can change their settings in Outlook to automatically accept (certain) invites.
Btw thanks for your snippet. Just what I needed.
Hi for calendar auto acceptance you should add the given lines in your code to create ics file.
ATTENDEE;PARTSTAT=ACCEPTED;CN= ExampleName1 c;EMAIL=example1#mail.com:MAILTO:example1#mail.com
ATTENDEE;PARTSTAT=ACCEPTED;CN= ExampleName2 c;EMAIL=example2#mail.comMAILTO:example2#mail.com
I have written code for sending mail with pdf file as attachment , mail sending is working. I used class.phpmailer.php. Below is my code.
$mpdf=new mPDF();
$mpdf->ignore_invalid_utf8 = true;
$stylesheet = file_get_contents('appstyle_pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($output);
$comname = preg_replace("/[^A-Za-z0-9]/","",$_POST['company']);
$name = $dirname.str_replace(" ","-",$comname)."_".$time_stamp.".pdf";
$mpdf->Output($name,"F");
$filename = basename($name);
$file_size = filesize($name);
$content = chunk_split(base64_encode(file_get_contents($name)));
$mail = new PHPMailer;
$msg = 'Message';
$body = '<html><body><p>' . $msg . '</p></body></html>'; //msg contents
$body = preg_replace("[\\\]", '', $body);
$mail->AddReplyTo('no-replay#enkapps.com', "ACIC");
$mail->SetFrom('orders#enkapps.com', "ACIC Order");
$address = 'narendar_medoju#tecnics.com'; //email recipient
$mail->AddAddress($address, "NAME");
$mail->Subject = 'SUBJECT of ACIC order form';
$mail->MsgHTML($body);
$mail->AddStringAttachment($content , $filename);
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent Successfully please check attachement!";
}
When I use the above code attachment is coming to mail but file is corrupting. The error message is like "Adobe reader could not open abc.pdf because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."
Why are you doing this?
$content = chunk_split(base64_encode(file_get_contents($name)));
...
$mail->AddStringAttachment($content , $filename);
That's completely unnecessary. Just do this:
$mail->addAttachment($name);
Also I suspect you are using an old version of PHPMailer; get the latest from github.
I have a simple contact form that works if I do not use smtp. I've tried to add smtp to use with mandrill, but it doesn't work. Emails aren't going through to mandrill.
I do not see any errors after sending either even if I enabled '$mail->SMTPDebug = 1;' I've tried on both local and live server environments.
<?php
require_once('../mail/class.phpmailer.php');
$emailaddress = "name#domain.com";
// Check for empty fields
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$ip = $_SERVER['REMOTE_ADDR'];
$message = $_POST['message'];
$subject = "Contact Form: $name";
$body = "You have received a new message from website.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nIP Address: $ip\n\nMessage:\n$message";
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.mandrillapp.com";
//$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->Host = "smtp.mandrillapp.com";
$mail->Port = 587;
$mail->Username = "username";
$mail->Password = "password";
$mail->CharSet = 'UTF-8';
$mail->SetFrom($email_address);
$mail->AddReplyTo($email_address);
$mail->Subject = "Contact Form: ".$_POST['name']." ";
$mail->MsgHTML($body);
$mail->AddAddress($emailaddress);
$mail->Send();
?>
I figured it out. I needed to also include the 'class.stmp.php' file as well. It doesn't have to be call, but needs to in the same folder as 'class.phpmailer.php.'