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.
Related
Does anyone know as how can I make a mail in perl using outlook and not send it just open it on the screen at the end of making the mail and let the user verify and send the mail. I am using Win32::OLE for making the mail.
PFB the code I am using:
sub Final_Mail_Outlook{
my($mailTo,$mailFrom,$subject,$body) = (#_);
my $Outlook = Win32::OLE->GetActiveObject('Outlook.Application') || Win32::OLE->new('Outlook.Application');
# Create Mail Item
my $item = $Outlook->CreateItem(0); # 0 = mail item.
unless ($item)
{
die "Outlook is not running, cannot send mail.\n";
}
$item->{'Subject'} = $subject;
$item->{'To'} = $mailTo;
$item->{'Body'} = $body;
$item->{'From'} = $mailFrom;
my $attach = $item->{'Attachments'};
my #outputFiles = glob("$OutputPath\\*.*");
foreach my $file (#outputFiles){
$attach->add($file);
}
$item->Send();
}
This sends the mail as I have called Send function, but I want to verify the mail generated. So is there a way to do so???
I just found an answer to it so thought of posting it also so that someone else needing an answer to this can get help. The key is to use the function Display() instead of Send(). PFB the modified code to open the mail and not send it.
sub Final_Mail_Outlook{
my($mailTo,$mailFrom,$subject,$body) = (#_);
my $Outlook = Win32::OLE->GetActiveObject('Outlook.Application') || Win32::OLE->new('Outlook.Application');
# Create Mail Item
my $item = $Outlook->CreateItem(0); # 0 = mail item.
unless ($item)
{
die "Outlook is not running, cannot send mail.\n";
}
$item->{'Subject'} = $subject;
$item->{'To'} = $mailTo;
$item->{'Body'} = $body;
$item->{'From'} = $mailFrom;
my $attach = $item->{'Attachments'};
my #outputFiles = glob("$OutputPath\\*.*");
foreach my $file (#outputFiles){
$attach->add($file);
}
$item->Display();
}
I am using php mail() (Via piped to program) and my goal is to simply get the email and scan the "from" header to filter it and then if it passes my "rules" or "checks" pass it along to the intended receiver. I have been able to use a sample code to get the mail and I can actually get my "test check" done. The problem I am having is that I cannot get the php mail() function to resend the mail as it was (plain or html). Every time i get my test mail, it comes with all the headers exposed and code. Not a nice and neat email. I also found out that I could encounter problems with this if there are attachments to the mail. I have seen alot of suggestions about going thru PHPMailer and I am willing to entertain that option. I just don't need this to get to complicated. here is the code I am using -
#!/usr/bin/php -q
<?php
$notify= 'myemail#mydomain.com'; // an email address required in case of errors
function mailRead($iKlimit = "")
{
if ($iKlimit == "") {
$iKlimit = 1024;
}
$sErrorSTDINFail = "Error - failed to read mail from STDIN!";
$fp = fopen("php://stdin", "r");
if (!$fp) {
echo $sErrorSTDINFail;
exit();
}
$sEmail = "";
if ($iKlimit == -1) {
while (!feof($fp)) {
$sEmail .= fread($fp, 1024);
}
} else {
while (!feof($fp) && $i_limit < $iKlimit) {
$sEmail .= fread($fp, 1024);
$i_limit++;
}
}
fclose($fp);
return $sEmail;
}
$email = mailRead();
$lines = explode("\n", $email);
$to = "";
$from = "";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
$headers .= $lines[$i]."\n";
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
$tst = substr($subject, -3);
if ($tst == "win" | $tst == "biz" | $tst == "net"){
$subject = $subject . "BAD ADDRESS";
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
mail('noreply#mydomain.com', $subject, $message);
?>
I am interested in learning, I am code savvy. Somewhat new to email formatting, but very understanding of PHP. Any help is appreciated. Thanx.
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.'
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!";
}
I have a email form for my website but here is the issue: when i receive an email, the subject line in my inbox shows whatever the user inputted as subject in the form. id like to override that so that whenever an email comes in. the subject in the email header is always "an inquiry from your website". In the message body, sure i don't mind their specific subject they entered but when I receive an email, id like consistency in my inbox.
this is the current code:
<?php session_start();
if(isset($_POST['Submit'])) { if( $_SESSION['chapcha_code'] == $_POST['chapcha_code'] && !empty($_SESSION['chapcha_code'] ) ) {
$youremail = 'xxxxxxxxx';
$fromsubject = 'An inquiry from your website';
$title = $_POST['title'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$mail = $_POST['mail'];
$address = $_POST['address'];
$city = $_POST['city'];
$zip = $_POST['zip'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$headers = "From: $nome <$mail>\r\n";
$to = $youremail;
$mailsubject = 'Message received from'.$fromsubject.' Contact Page';
$body = $fromsubject.'
The person that contacted you is '.$fname.' '.$lname.'
Address: '.$address.'
'.$city.', '.$zip.', '.$country.'
Phone Number: '.$phone.'
E-mail: '.$mail.'
Subject: '.$subject.'
Message:
'.$message.'
|---------END MESSAGE----------|';
echo "Thank you for inquiring. We will contact you shortly.<br/>You may return to our <a href='/index.html'>Home Page</a>";
mail($to, $subject, $body, $headers);
unset($_SESSION['chapcha_code']);
} else {
echo 'Sorry, you have provided an invalid security code';
}
} else {
echo "You must write a message. </br> Please visit our <a href='/contact.html'>Contact Page</a> and try again.";
}
?>
It appears as though you have set a variable called $subject elsewhere.
$subject = $_POST['subject'];
and then use that same variable to send your mail.
mail($to, $subject, $body, $headers);
Try creating another variable for the second use or changing it prior to suit your needs.