Use PHPmailer to send attachment - php

I'm using PHPmailer library to send emails and I need to send an attachment.
Currently the file is stored on the server and I have the link to the file stored in var $link.
I'm using the following to try and add the attachment but the email arrives with no attachment:
$phpmailer->AddAttachment('$link');
I have also tried it with a hardcoded path instead of my variable:
$phpmailer->AddAttachment('http://mysite.co.uk/link/to/my/file.pdf');
The email shows up but does not have any attachment.
I have tried using phpmailerException to grab any errors but get no response.
How else can I send an attachment with PHPmailer?
Full PHP code:
require_once 'library/PHPMailer.php';
$phpmailer = new PHPMailer();
$phpmailer->isSMTP(); //switch to smtp
$phpmailer->Host = 'smtp.sendgrid.net';
$phpmailer->SMTPAuth = true;
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->Port = 465;
$phpmailer->Username = 'username';
$phpmailer->Password = 'password';
$phpmailer->AddAttachment('http://mysite.co.uk/blah/cv.pdf');
//$phpmailer->AddAttachment('$link');
$subject = 'Job Application';
$messageConfirmation = "The <b> 'Apply for Job' </b> form has recently been completed on <b>www.mysite.com.</b><br/><br/> <b>Please see contact details below:<br /><br/> </b>";
$messageConfirmation.= "<b>Applying for:</b> $title <br/><br/>";
$messageConfirmation .= "<b>Name:</b> $name <br/><br/><b>Surname:</b> $surname <br/><br/> <b>Email:</b> $email <br/><br/> <b>Comment:</b> $comment <br/><br/>";
$messageConfirmation .= "<b>CV:</b> $link<br /><br />";
$messageConfirmation .= "Please can you call them back in the next 24 hours. <br/><br/> Thank you \n\nMy Site<br/><br/>";
$imgheader = 'http://blah.co.uk/blah/wp-content/uploads/2014/11/header.png';
$imgfooter = 'http://blah.co.uk/blah/wp-content/uploads/2014/11/footer.png';
$message = '<!DOCTYPE HTML>'.
'<head>'.
'<meta http-equiv="content-type" content="text/html">'.
'<title>Email notification</title>'.
'</head>'.
'<body>'.
'<div id="header" style="width: 600px;height: auto;margin: 0 auto;color: #fff;text-align: center;font-family: Open Sans,Arial,sans-serif;">'.
'<img src="'.$imgheader.'" >'.
'</div>'.
'<div id="outer" style="width: 600px;margin: 0 auto;margin-top: 10px;">'.
'<div id="inner" style="width: 600px;margin: 0 auto; padding-left: 20px;background-color: #fff;font-family: Open Sans,Arial,sans-serif;font-size: 13px;font-weight: normal;color: #444;margin-top: 10px;">'.
'<p>'.$messageConfirmation .'</p>'.
'</div>'.
'</div>'.
'<div id="footer" style="width: 600px;height: auto;margin: 0 auto;text-align: center;padding: 10px;font-family: Verdena;">'.
'<img src="'.$imgfooter.'" >'.
'</div>'.
'</body>';
$phpmailer->IsHTML(true);
$phpmailer->AddAddress(CONTACTUSFORMEMAIL);
$phpmailer->From = CONTACTUSFORMEMAIL;
$phpmailer->FromName ='blah';
$phpmailer->WordWrap = 50; // set word wrap to 50 characters
$phpmailer->Subject = $subject;
$phpmailer->Body = $message;
$phpmailer->Send();
$data['success'] = true;
$data['message'] = 'Thank you for your application';

The Problem is that the function AddAttachment uses the function is_file() and is file returns false when accessing URLs (this also applies to relative URLs), is_file() only accepts filepaths. So normally phpmailer should add an error to the error container.

Hi Please try the following code
<?php
$mail = new PHPMailer();
$mail->From = $email_from;
$mail->SetFrom($email_from, $name_from);
$mail->AddAddress($email_to, $name_to);
$mail->AddReplyTo($email_from, $name_from);
$mail->MsgHTML($message_goes_here);
$mail->Subject = $your_subject;
$mail->AddAttachment($file_name_goes_here);
if($mail->Send()) {
} else {
echo "\r\nMail not sent. " . $mail->ErrorInfo;
}
?>

I know it might sound like a radical idea, but you could try reading the docs, or perhaps checking return values of functions, maybe even trying an up to date version of PHPMailer, or basing your code on a recent example.
PHPMailer will only throw exceptions if you enable them at instantiation with $mail = new PHPMailer(true);, and as #TheGreenKey said, it will set an error notice and produce an error message if you enable debugging.
If you want to add URL contents as an an attachment, you can do this:
$mail->addStringAttachment(file_get_contents('http://mysite.co.uk/link/to/my/file.pdf'), 'cv.pdf');`
That's never going to be fast, reliable or efficient though.

The method AddAttachment receives the path of the file.
If you see the source code, you will see that it uses fopen function to open the file, so, I think it doesn't work with links, you should download the file by yourself and pass the path to the function.

send any type of attachment using phpmailer.
<?php
require 'PHPMailer/class.phpmailer.php';
if(isset($_POST['send']))
{
$file_name = $_FILES['file']['name']; //attachment
$file_tmp =$_FILES['file']['tmp_name'];
$abc=microtime();
$path="upload/$abc".$file_name;
move_uploaded_file($file_tmp,$path); //moving attachment to upload folder
$mail = new PHPMailer(true);
$mail->IsSMTP();
$mail->SMTPAuth = false;
$mail->Port = 25;
$mail->Host = "localhost";
$mail->Username = "webmail_username";
$mail->Password = "webmail_password";
$mail->IsSendmail();
$mail->From = "abc#your.com";
$mail->FromName = "your.com";
$mail->AddAddress('receiver_emailid');
$mail->Subject = "Thank you for contacting US";
$mail->WordWrap = 80;
$body="Thank You For Contacting Us";
$mail->MsgHTML($body);
$mail->IsHTML(true);
$mail->AddAttachment($path,$file_name); //Attachment File
if(!$mail->Send())
{
echo "Mail Not Sent";
}
else
{
echo '<script language="javascript">';
echo 'alert("Thank You Contacting Us We Will Response You As Early Possible")';
echo '</script>';
}
}
for more details :- click here

Related

Include an image in email PHP

I'm experiencing an issue where only the text from body is appearing the image is coming through broken, does anyone see where I might be going wrong?
<?php
require("php/PHPMailer.php");
require("php/SMTP.php");
if (isset($_GET['email'])) {
$emailID = $_GET['email'];
if($emailID = 1){
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "";
$mail->Password = "";
$mail->SetFrom("");
$mail->Subject = "Test";
$mail->Body = '<html><body><p>My Image</p><img src="images/EmailHeader.png" width="75%"></body></html>';
$mail->AddAddress("");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
else {
echo "Message has been sent";
}
}
}
?>
The image URL you are using is relative. You will need to use the full URL.
Instead of:
<img src="images/EmailHeader.png" width="75%">
It needs to be an absolute URL that the public can see, such as:
<img src="https://image-website.com/images/EmailHeader.png" width="75%">
You can not upload image with relative path in Email. You have to use full path because when the mail is send it require whole path to fetch the image content.,
Replace this line,
$mail->Body = '<html><body><p>My Image</p><img src="images/EmailHeader.png" width="75%"></body></html>';
With this line,
$mail->Body = '<html><body><p>My Image</p><img src="http://your-domainname.com/images/EmailHeader.png" width="75%"></body></html>';
Another option is that you can use use base64 images for it. But in your case you have to give full path.

How to use phpmailer and send mail as html from ckeditor

I'm use phpmailer to sending email, I have problems when inserting the contents of the html code on the form ckeditor, but data sent to the e-mail text only.
This is my code:
require_once ('class.phpmailer.php');
$mail = new PHPMailer(true);
if (isset($_POST['btn_send']))
{
$smtp_username = strip_tags($_POST['username']);
$smtp_password = strip_tags($_POST['password']);
$ssl_port = strip_tags($_POST['port']);
$my_smtp = strip_tags($_POST['host']);
$my_ssl = strip_tags($_POST['type']);
$realname = strip_tags($_POST['realname']);
$subject = strip_tags($_POST['subject']);
$body = strip_tags($_POST['editor']);
$emaillist = strip_tags($_POST['emaillist']);
//...now get on with sending...
try
{
//$mail->isSendmail();
$mail->isSMTP();
$mail->Body = ($body);
$mail->isHTML(true);
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = "$my_ssl";
$mail->Host = "$my_smtp";
$mail->Port = "$ssl_port";
$mail->AddAddress($emaillist);
$mail->Username = "$smtp_username";
$mail->Password = "$smtp_password";
$mail->SetFrom("$smtp_username", "$realname");
$mail->AddAddress($emaillist);
$mail->epriority = "3";
$mail->AddReplyTo("$smtp_username");
$mail->Subject = "$subject";
$mail->encode = ("yes");
$mail->CharSet = "utf-8";
if($mail->Send())
{
$msg = "<div class='alert alert-success'>
Hi,<br /> bro mail terkirim ke ".$emaillist."
</div>";
}
}
catch(phpmailerException $ex)
{
$msg = "<div class='alert alert-warning'>".$ex->errorMessage()."</div>";
}}
I do not know what went wrong
You need edit this row
$body = strip_tags($_POST['editor']);
to $body = $_POST['editor'];
And add this line before mail send
$mail->isHTML(true);
Function strip_tags removes html markup.
But you need filter value another way.
Please edit this line
$body = strip_tags($_POST['editor']); to $body = $_POST['editor'];
the strip_tags() function will remove all tags from your posted value. The you cant get the the html tags.
Please enable html in your PHP mailer by adding this line
$mail->isHTML(true);
So please edit the code and try this way.
This is working fine in my case.
If you are using Codeigniter, you might face a problem if doing:
$body = $this->input->post('some_field_with_html_body');
You can fix it by doing:
$body = $_POST['some_field_with_html_body'];

PHPMailer doesn't show HTML

I am building a bulk email tool to address a list of our clients regarding some upcoming migrations. Our current mass mail tool doesn't quite cut it in this particular case, where I have opted to just build one instead.
I am using TinyMCE to provide an editor for the email message body and passing this along to PHPMailer to send out. Everything is working great except the html is not displayed properly when viewed in a client such as Outlook. I have made absolutely sure $mail->isHTML(true) is set so I am at a loss now.
I echo out the value of $message in the bulk_mail_sender() function and its correct. If I paste this string as $mail->Body it works. If I have $message set as $mail->Body however, it turns into all sorts of strange characters.
Message Source:
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><p>Hi there,</p>
<p>Â </p>
<p>What is up foo</p>
Code:
function bulk_mail_sender($vars, $emails, $subject, $message)
{
foreach ($emails as $email)
{
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $vars['opt_host']; // Specify main SMTP Server
$mail->Port = $vars['opt_port']; // TCP port
$mail->Username = $vars['opt_user']; // SMTP Username
$mail->Password = $vars['opt_pass']; // SMTP Password
$mail->SMTPSecure = $vars['opt_type']; // Enable TLS / SSL encryption
$mail->setFrom($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addAddress($email);
$mail->addReplyTo($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $message;
if(!$mail->send())
{
echo 'Message failed to send to ' . $email;
echo 'Mailer Error: ' . $mail->ErrorInfo . '</br></br>';
}
else
{
echo 'Message has been sent to ' . $email . '</br>';
}
}
}
function bulk_mail_output($vars)
{
if (!empty($_POST))
{
$subject = $_POST['subject'];
$message = $_POST['message'];
$emails = $_POST['emails'];
$emails = explode(PHP_EOL, $emails);
bulk_mail_sender($vars, $emails, $subject, $message);
}
else
{
echo '<form method="POST" action="">';
echo 'Subject: <input type="text" name="subject" id="subject"></br></br>';
echo '<textarea rows="10" cols="100" name="message" id="message"></textarea></br></br>';
echo '<h3>Email Addresses</h3>';
echo '<textarea rows="10" cols="100" name="emails" id="emails"></textarea></br></br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
echo '<script language="javascript" type="text/javascript" src="../includes/jscript/tiny_mce/tiny_mce.js"></script>
<script language="javascript" type="text/javascript">
tinyMCE.init({
mode: "exact",
elements: "message",
theme: "advanced",
entity_encoding: "raw",
convert_urls: false,
relative_urls: false,
plugins: "style,table,advlink,inlinepopups,media,searchreplace,contextmenu,paste,directionality,visualchars,xhtmlxtras",
theme_advanced_buttons1: "cut,copy,paste,pastetext,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,formatselect,fontselect,fontsizeselect,|,search,replace",
theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,|,forecolor,backcolor,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,media,|,ltr,rtl,cleanup,code,help",
theme_advanced_buttons3: "", // tablecontrols
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true
});
function toggleEditor(id)
{
if (!tinyMCE.get(id))
tinyMCE.execCommand(\'mceAddControl\', false, id);
else
tinyMCE.execCommand(\'mceRemoveControl\', false, id);
}
</script>';
}
}
While I couldn't ever find a way to fix this within TinyMCE, the workaround used was to just wrap my $message variable in the html_entity_decode function when setting it to the mail body. I would have preferred to pass the data from TinyMCE properly the first time, however the entity encoding cannot be fully disabled for some reason.
$mail = new PHPMailer;
$mail->CharSet = "UTF-8";
$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Host = $vars['opt_host']; // Specify main SMTP Server
$mail->Port = $vars['opt_port']; // TCP port
$mail->Username = $vars['opt_user']; // SMTP Username
$mail->Password = $vars['opt_pass']; // SMTP Password
$mail->SMTPSecure = $vars['opt_type']; // Enable TLS / SSL encryption
$mail->setFrom($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addReplyTo($vars['opt_sender_email'], $vars['opt_sender_name']);
$mail->addAddress($email);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = html_entity_decode($message);
if(!$mail->send())
{
echo 'Message failed to send to ' . $email;
echo 'Mailer Error: ' . $mail->ErrorInfo . '</br></br>';
}
else
{
echo 'Message has been sent to ' . $email . '</br>';
}

PHPMailer - HTML content getting blocked

I'm having trouble trying to send out a HTML email.
I can:
Connect to the server fine with SMTP and SSL
I can send a simple HTML email fine
But anything that resembles what I would call "normal" HTML content gets blocked EVERY TIME!
Anyone suggest anything to try? I don't see anything wrong with what I've done, but obvs there's something there...
So this code gets blocked for me:
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = "xxxx";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Username = "xxx";
$mail->Password = "xxx";
$mail->setFrom('xxx', 'Me');
$mail->addReplyTo('xxx', 'Me');
$mail->addAddress('xxx#me.com');
$mail->Subject = 'Here come the bastards';
$mail->CharSet = 'UTF-8';
$mail->msgHTML('
<html>
<body>
<table style="width: 100%;background-color: #60bb98;">
<tr>
<td>
<a href="#">
<img src="http://mystorymycontent.com/wp-content/themes/MSMC/img/logo-new.gif" />
</a>
</td>
</tr>
<tr>
<td>HELLO EVERYONEZZZ
</td>
</tr>
</table>
</body>
</html>
');
$mail->AltBody = 'Heres all the copy from the HTML verison of the email. Theres a few lines about things and that';
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
I'm using PHPMailer to send HTML mails and I had to do this :
$mail->IsHTML();
From the doc :
Before sending this out, we have to modify the PHPMailer object to
indicate that the message should be interpreted as HTML.
Technically-speaking, the message body has to be set up as
multipart/alternative. This is done with: $mail->IsHTML(true);
i agree with #FLX but in the phpmailer example it's written this way
$email ->IsHTML();
not
$mail ->IsHTML();
or the variable with you create the instance.
$VARIABLE = new PHPMailer();
.
.
.
.
$VARIABLE ->IsHTML();
it's just a suggestion

attachment is not sent with phpmailer

I'm trying to send an attachment with the phpMailer script.
Everything is working correctly since my email is sent correctly, however I do have a problem with an attachment that is not sent.
HTML part:
<p>
<label>Attachment :</label>
<input name="doc" type="file">
</p>
PHP:
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '*****';
$mail->SMTPAuth = true;
$mail->Port = 465;
$mail->Username = '*****';
$mail->Password = '*****';
$mail->SMTPSecure = 'ssl';
$mail->From = $_POST["name"];
$mail->FromName = 'Your Name';
$mail->Subject = 'Message Subject';
$mail->addAddress('*****');
$mail->addAttachment($_FILES["doc"]);
$mail->isHTML(true);
$mail->Subject = 'Here is the subject';
$mail->Body = "You got a new message from your website :
Name: $_POST[name]
Company: $_POST[company]
Phone: $_POST[phone]
Email: $_POST[email]
Message: $_POST[message]";
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<p> <img src="img/correct.png" alt="icon" style=" margin-right: 10px;">Thank you! We will get back to you soon.</p>
</body>
</html>
Try:
if (isset($_FILES['doc']) &&
$_FILES['doc']['error'] == UPLOAD_ERR_OK) {
$mail->AddAttachment($_FILES['doc']['tmp_name'],
$_FILES['doc']['name']);
}
Basic example can also be found [here](https://code.google.com/a/apache-extras.org/p/phpmailer/wiki/AdvancedMail).
The function definition for `AddAttachment` is:
public function AddAttachment($path,
$name = '',
$encoding = 'base64',
$type = 'application/octet-stream')
Please have a look about how PHP file uploads work. This array key:
$_FILES["doc"]
... will never contain a file. At most, it'll contain an array with information about where to find the file.
Untested solution, but should work:
change
$mail->addAttachment($_FILES["doc"]);
to
$mail->addAttachment($_FILES["doc"]["tmp_name"], $_FILES["doc"]["name"], "base64", $_FILES["doc"]["tmp_type"]);
However, please consider learning php upload file handling as already commented by others. Don't use user input without validation. Never!

Categories