Phpmailer sending attachments, but not the body - php

I have a form that im trying to get emailed on submit using PHPmailer. For some reason, phpmailer is sending the attachments of the email, but not the body/message. Heres my phpmailer file..
$name = "Purchase Form";
$email_subject = "New Purchase Ticket";
$body = "geg";
foreach ($_REQUEST as $field_name => $value){
if (!empty($value)) $body .= "$field_name = $value\n\r";
}
$Email_to = "jonahkatz#yahoo.com"; // the one that recieves the email
$email_from = "No reply!";
//
//==== PHP Mailer With Attachment Func ====\\
//
function SendIt() {
//
global $attachments,$body,$name,$Email_to,$email_subject,$email_from;
//
$mail = new PHPMailer();
$mail->IsQmail();// send via SMTP
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
$mail->IsHTML = true;
$mail ->MsgHTML($body);
$mail->AltBody = 'to view blah';
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
if(move_uploaded_file($file['tmp_name'], $target_path)) {
echo "the file ".basename($file['name'])." has been uploaded";
}else {
echo "there was an error";
}
$mail->AddAttachment($target_path);
}
$mail->Subject = $email_subject;
if(!$mail->Send())
{
}
//
{echo "Message has been sent";}
foreach($_FILES as $key => $file){
$target_path = "uploads/";
$target_path = $target_path .basename($file['name']);
unlink($target_path);}
}
SendIt();
}
?>
Any input? Thanks.

->MsgHTML() doesn't set the body. It returns a modified version with inlined-img urls and whatnot and DOES set the AltBody to a text-version of the HTML. You still need to do
$mail->Body = $body;

Related

utf-8 for attachment in PHPmailer

I've got problem with attachment name, if there are polish language diacritical signs, it won't display those signs.
I added just below php mailer class $mail->CharSet = 'UTF-8'; and it works for email body text( without it I had the same problem), but not for attachments. Also I had a similar problem with user name, but solved it with utf8_decode() function. Unfortunately that function is not working with attachment's name in my case.
<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
//Load Composer's autoloader
require 'autoload.php';
//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
//$mail->addCustomHeader('Content-Type', 'text/plain;charset=utf-8');
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$honeypot = $_POST['honey'];
$user_name = utf8_decode($_POST['name']);
$user_email = $_POST['email'];
$user_message = $_POST['message'];
$user_phone = $_POST['phone'];
$honeypot = trim($_POST["honey"]);
$max_size = 2 * 1024 * 1204; //2mb
$attachment = $_FILES['uploaded-file'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(!empty($honeypot)) {
echo "NO SPAM!";
exit;
} else {
$mail = new PHPMailer; //From email address and name
$mail->isMail();
//sender
$mail->From = $user_email;
$mail->FromName = $user_name;
//recipient
$mail->addAddress("jaroslaw.mor#gmail.com");
//mail subject
$mail->Subject = "Zapytanie ze strony www";
$mail->isHTML(true);
//body mail
$mail->Body = "Telefon:$user_phone<br><br>Treść wiadomośći:<br>$user_message";
$mail->AltBody = "Telefon:$user_phone\n$content";
//attachment
if(isset($attachment)) {
for ($i = 0; $i < count($_FILES['uploaded-file']['name']); $i++) {
if ($_FILES['uploaded-file']['error'][$i] !== UPLOAD_ERR_OK) continue;
$file_TmpName = $_FILES['uploaded-file']["tmp_name"][$i];
$file_name = utf8_decode( $_FILES['uploaded-file']["name"][$i]);
if ($_FILES['uploaded-file']['size'][$i] > $max_size) {
echo "file is too big";
die();
}
else{
move_uploaded_file($file_TmpName, "uploads/" . $file_name);
$mail-> AddAttachment("uploads/". $file_name);
}
}//for
}//isset
if(!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
exit();
}
else {
header("Location: sent.html");
exit();
}//if send else
}//honey else end
}//post end
You can try to add this code before attachment upload:
setlocale( LC_ALL, "pl_PL.UTF-8" );
Try force encoding for attachment:
$mail->AddAttachment("uploads/", $file_name, $mail::ENCODING_BASE64, PHPMailer::filenameToType($file_name).'; charset=utf-8');
I tried all methods from here - without a positive result. By the accident I opened PHPMailer.php and noticed that there are some options connected with charset encoding, changed settings there and now it works.
Thx all for clues.

PHPmailer not sending mail when message field is empty but is not required?

http://nodeiterator.pl/
Why my php mailer script is not sending mail when message field is empty but is not required ? I get the message "please try again later". What am I missing ?
This is my script:
$msg = "";
use PHPMailer\PHPMailer\PHPMailer;
include_once "phpmailer/src/PHPMailer.php";
include_once "phpmailer/src/Exception.php";
if (isset($_POST['submit'])) {
$subject = $_POST['subject'];
$email = $_POST['email'];
$message = $_POST['message'];
if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != "") {
$file = "attachment/" . basename($_FILES['attachment']['name']);
move_uploaded_file($_FILES['attachment']['tmp_name'], $file);
} else
$file = "";
$mail = new PHPMailer();
$mail->addAddress('piterdeja#gmail.com');
$mail->setFrom($email);
$mail->Subject = $subject;
$mail->isHTML(true);
$mail->Body = $message;
$mail->addAttachment($file);
if ($mail->send())
$msg = "Your email has been sent, thank you!";
else
$msg = "Please try again!";
}
I don't think PHPMail by default will let you send an email with an empty body, but you can just go:
$mail->AllowEmpty = true;
Check the error returned:
if(!$mail->Send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
}
Normally phpmailer does not accept an empty body, you must force it using the attribute $mailer->AllowEmpty = true;

Attachments working intermittently

I am having issues with my phpMailer script. I can email from the script, I can even send attachments from the script. However, it only works SOMETIMES and not at other times. I tried changing servers and I have the same issues so I am assuming that it is a coding issue.
when It does not work, the emails still go thorough but it is stripped from any attachments.
The attachments are definitely making it onto the server in the same location and then this script is sent an array of attachments which it then adds onto the message.
In one instance the same code and same files will send and not send! Very confusing! Usually some will send for awhile and then some will not for awhile.
Here is the code:
<?php
include('connection.php');
require_once('PHPMailer/PHPMailerAutoload.php');
class Mailer extends PHPMailer {
public function copyToFolder($folderPath) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{mail.server.com:143/novalidate-cert}" . $path , $this->Username, $this->Password) or die(mysql_error());
imap_append($imapStream, "{mail.server.com:143/novalidate-cert}" . $path, $message)or die(mysql_error());
}
imap_close($imapStream);
}
}
$from = $_POST['from'];
$username = $from;
$grabPassword = mysql_query("SELECT * FROM `email_pw_db` WHERE `emailaddress` = '$from'");
$fetchPassword = mysql_fetch_assoc($grabPassword);
$password = $fetchPassword['password'];
$company = $_POST['to'];
$toemail = $_POST['toemail'];
$from = $username;
$namefrom = $_POST['from'];
$subject = $_POST['subject'];
$cc = trim($_POST['cc']);
$bcc = trim($_POST['bcc']);
$message = $_POST['body'];;
$attachments = $_POST['attachments'];
$mail = new Mailer();
$body = $message;
/*Create a new email*/
$mail = new Mailer();
$mail->isSMTP();
$mail->Host = 'mail.server.com';
$mail->Username = $username;
$mail->Password = $password;
$mail->From = $from;
$mail->AddReplyTo($from,$namefrom);
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SetFrom($from, $namefrom);
$mail->AddReplyTo($from,$namefrom);
$address = $toemail;
$mail->AddAddress($address, $company);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if($cc!=''){
$mail->addCC($cc);
}
//CC EMAILS//
$breakOutCC = explode(',', $cc);
$countBreakOut = count($breakOutCC);
$i = 0;
while($i <$countBreakOut)
{
$mail->addCC($breakOutCC[$i]);
$i++;
}
$breakOutBCC = explode(',', $bcc);
$countBreakOutBCC = count($breakOutBCC);
$i = 0;
while($i <$countBreakOutBCC)
{
$mail->addBCC($breakOutBCC[$i]);
$i++;
}
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
$mail->AddAttachment("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$errorMessage = $mail->ErrorInfo;
header( 'Location: email-software.php?dialog=Whoops Something Happened- '.$errorMessage ) ;
} else {
//$mail->copyToFolder(); //save email
$mail->copyToFolder("Sent"); // Will save into Sent folder
$attachments = $_POST['attachments'];
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
unlink("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
header( 'Location: email-software.php?dialog=email sent' ) ;
}
?>

Files will corrupt when send by php mailer

I use this php mailer
every things are O.k. but when I attach a file, corrupted file receive in destination email. for example when I send a pdf file receiver can't open it.
and this is my code in using phpmailer:
$target_path = "upload_files/";
$target_path = $target_path . basename( $_FILES['attach']['name']);
if(move_uploaded_file($_FILES['attach']['tmp_name'], $target_path)) {
} else{
}
//eupload file end
require_once 'phpmailer/phpmailer.inc.php';
$mail = new PHPMailer();
$body = $message;
$body = eregi_replace("[\]",'',$body);
$mail->AddReplyTo($email, $fname." ".$lname);
$mail->FromName = $fname." ".$lname;
$mail->From = $email;
$mail->AddAddress("email address", "some one");
$mail->Subject = "something";
$mail->body = $body;
$mail->AddAttachment($target_path); // attachment
if(!$mail->Send()) {
} else {
}
Your PHPMailer have critical errors try it
Must be your Header include file's are wrong
becouse this is the basic mistake in attachments
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
:P

phpMailer Attachment not working

this is my first post and I hope that I can get some help regarding adding an attachment field in my phpMailer contact form. I have already added an uploader [browse] bar in the html website but I don't know how to link it with the phpmailer. do I have to declare it at the package which is phpmailer.php or do something with it?
I would really appreciate some help. Below is my desperate attempt.
Snippet from the code:
<?
$body = ob_get_contents();
$to = 'xxx#xxxx.com>';
$email = $email;
$subject = $subject;
$fromaddress = "xxx#xxxx.com";
$fromname = "Online Contact";
require("phpmailer.php"); //<<this is the original pack
$mail = new PHPMailer();
$mail->From = "xxx#xxxx.com";
$mail->FromName = "My Name";
$mail->AddBCC("xxx#xxxx.com","Name 1");
$mail->AddAddress( $email,"Name 2");
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AltBody = "This is the text-only body";
// attachment
$mail->AddAttachment('uploadbar', 'new_file.pdf'); // the name of my html uploader is uploadbar, clicking browse to locate a file
if(!$mail->Send()) {
$recipient = 'xxx#xxxx.com';
$subject = 'Contact form failed';
$content = $body;
mail($recipient, $subject, $content, "From: xxx#xxxx.com\r\nReply-To: $email\r\nX-Mailer: DT_formmail");
exit;
}
?>
Had the same problem, try this
$mail->AddAttachment($_SERVER['DOCUMENT_ROOT'].'/file-name.pdf');
First, make sure your upload form has enctype='multipart/form-data' as in <form method=post action=file.php enctype='multipart/form-data'>.
then, use this code in your phpmailer handler file
foreach(array_keys($_FILES['files']['name']) as $key) {
$source = $_FILES['files']['tmp_name'][$key];
$filename = $_FILES['files']['name'][$key];
$mail->AddAttachment($source, $filename);
}
Make sure attachment file name should not contain any special character and check the file path also correct.
eg: [file name.pdf] Should be like [filename.pdf]

Categories