I want to send a file via PhpMailer. If the file has extension .txt or .png ecc.. It sends me the email with the file (it works) but if I want to send a .pdf I don't receive the email ... this is a part of my PHP code:
$Name = $_POST['Name'];
$Email = $_POST['Email'];
$Surname = $_POST['Surname'];
$Residence = $_POST['Residence'];
$Phone = $_POST['Phone'];
$Name = filter_var($Name, FILTER_SANITIZE_STRING);
$Surname = filter_var($Surname, FILTER_SANITIZE_STRING);
$Email = filter_var($Email, FILTER_SANITIZE_EMAIL);
$Residence = filter_var($Residence, FILTER_SANITIZE_STRING);;
$Phone = filter_var($Phone, FILTER_SANITIZE_STRING);;
$mail = new PHPMailer();
$mail->SMTPAuth = true;
$mail->Host = "smtp.gmail.com"; // SMTP server
$mail->SMTPSecure = "ssl";
$mail->Username = "xxx"; //account with which you want to send mail. Or use this account. i dont care :-P
$mail->Password = "xxx"; //this account's password.
$mail->SetFrom('xxx');
$mail->Port = "465";
$mail->isSMTP(); // telling the class to use SMTP
$rec1="xxx"; //receiver. email addresses to which u want to send the mail.
$mail->AddAddress($rec1);
$mail->Subject = "Eventbook";
$mail->isHTML(true);
$mail->Body = "<h1>Contact from Website</h1>
<ul>
<li>Nome: {$Name}</li>
<li>Cognome: {$Surname}</li>
<li>Comune di residenza: {$Residence}</li>
<li>Email: {$Email}</li>
<li>Telefono: {$Phone}</li>
</ul>";
$mail->WordWrap = 200;
$mail->addAttachment($_FILES['curriculum']['tmp_name'], $_FILES['curriculum']['name']);
if(!$mail->Send()) {
echo 'Message was not sent!.';
$errore = $mail->ErrorInfo;
echo 'Mailer error: ' . $mail->ErrorInfo;
} else {
echo //Fill in the document.location thing
'<script type="text/javascript">
if(confirm("Your mail has been sent"))
document.location = "/";
</script>';
}
This is the JS script with ajax:
var formData = new FormData();
formData.append('Name', $('#Name').val());
formData.append('Surname', $('#Surname').val());
formData.append('Residence', $('#Residence').val());
formData.append('Email', $('#Email').val());
formData.append('Phone', $('#Phone').val());
formData.append('Curriculum', $('#Curriculum')[0].files[0]);
$.ajax({
method: 'POST',
url: "scripts/register.php",
data: formData,
processData: false,
contentType: false,
success: function (Curriculum) {
alert('Success');
}
});
This is the HTML file input part:
<input type="file" name="Curriculum" id="Curriculum" style="display: none;" class="form__input" />
<label for="Curriculum" id="LabelCurriculum" class="form__input" style="background-color: white; display: block; width: 100%; padding: 20px; font-family: Roboto; -webkit-appearance: none; border: 0; outline: 0; transition: 0.3s;">Click to upload</label>
It seems that It can't upload due to its size maybe ... because I uploaded .txt and .png of 50KB but the .pdf is 1MB
UPDATE: When I debug I can see that the file is uploaded , so I think that it don't send the email... why????
Don't use values directly from the $_FILES superglobal as they are potentially forgeable. You must validate them using the built-in move_uploaded_file or is_uploaded_file functions. The PHP docs on handling file uploads are excellent, so do what they say.
Base your code on the send file upload example provided with PHPMailer which uses move_uploaded_file before using the file. It's also a good idea to not use user-supplied filenames so as to avoid the possibility of file overwrite attacks - in the example you'll see it uses a hash of the filename (which will always be safe) to avoid doing that.
It's a good idea to check return values from critical functions - addAttachment() returns false if it can't read the file you ask it to read, for example:
if (!$mail->addAttachment($filename, 'file.pdf')) die('Could not read file!');
Look at the file upload size limit set in your PHP config, and mirror that in your form - see here and here. If you exceed this limit, you may find that you still have an entry in your $_FILES array, but it may point to an empty or non-existent file, which is another reason to validate and check return values. You can var_dump($_FILES) to see exactly what your script is receiving - it may not contain what you think it should.
I can see that you've based your code on a very old example, so make sure you're running the latest version of PHPMailer too.
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 15 days ago.
I have made a regular HTML form with POST method and action referring to a PHP page with a code I found here on Stackoverflow. Also, I have added a javascript validation.
I have checked everything and to my knowledge, everything is fine. Yet, I never receive the email. At first, I thought it was the javascript intervening with the $_POST['submit'] but even without the validation, the form doesn't send me the data. Furthermore, the PHP has an echo line which doesn't show either when trying to submit the form without the validation. I have googled that this might have something to do with the code being outdated as it uses a direct mail() instruction. Still, I would like to send the form to a specific email. Is there a way to do it? Can you help me with the right code?
I even tried using direct HTML mailto: attribute but not even that worked.
Finally, I tried using some SMTP server code I found in other questions here but I can't seem to figure it out. On the server side (Gmail), I allowed POP3 and IMAP in my Gmail account.
I know there are similar questions out there but none of the answers work for me. As I am a noob, I would appreciate the simplest solution involving only PHP coding or Gmail setting. I don't wish to install or incorporate any third-party stuff.
Thanks in advance.
This is what I have tried:
HTML:
<form method="post" action="send.php" id="qForm" enctype="multipart/form-data" onsubmit="validateCaptcha()" >
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="message">Your message:</label>
<textarea id="message" maxlength="500" type="text" name="message" required
placeholder="Write your message here."></textarea>
<div id="captcha"></div>
<input type="text" placeholder="Copy the code here." id="cpatchaTextBox"/>
<input type="submit" value="SEND" name="submit" id="submit" >
</form>
PHP (send.php):
<?php
if(isset($_POST['submit'])){
$to = "myname#gmail.com"; // this is my Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Web message";
$message = $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$headers,$message);
mail($from,$subject,$headers2,$message); // sends a copy of the message to the sender
echo "Message sent. " . "\n\n" . " Thank you, " . $name . ", we will be in touch.";
}
?>
The extra SMTP code I found here:
<?php
$mail->Mailer = "smtp";
$mail->Host = "ssl://smtp.gmail.com";
$mail->Port = 465;
$mail->SMTPAuth = true;
$mail->Username = "myname#gmail.com";
$mail->Password = "mypassword123";
?>
JAVASCRIPT validation:
var code;
function createCaptcha() {
//clear the contents of captcha div first
document.getElementById('captcha').innerHTML = "";
var charsArray =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ#!#$%^&*";
var lengthOtp = 6;
var captcha = [];
for (var i = 0; i < lengthOtp; i++) {
//below code will not allow Repetition of Characters
var index = Math.floor(Math.random() * charsArray.length + 1); //get the next character from the array
if (captcha.indexOf(charsArray[index]) == -1)
captcha.push(charsArray[index]);
else i--;
}
var canv = document.createElement("canvas");
canv.id = "captcha";
canv.width = 100;
canv.height = 50;
var ctx = canv.getContext("2d");
ctx.font = "25px Georgia";
ctx.strokeText(captcha.join(""), 0, 30);
//storing captcha so that can validate you can save it somewhere else according to your specific requirements
code = captcha.join("");
document.getElementById("captcha").appendChild(canv); // adds the canvas to the body element
}
function validateCaptcha() {
event.preventDefault();
debugger
if (document.getElementById("cpatchaTextBox").value == code) {
alert("Thank you for your message. We will be in touch.");
window.location.reload();
}else{
alert("Sorry. Try it again.");
createCaptcha();
}
}
When the form starts to submit you run validateCaptcha.
The first thing you do is call event.preventDefault which prevents the form from submitting.
Later you call window.location.reload which reloads the page, using a GET request, so $_POST['submit']) is not set.
If you want the data to submit, don't cancel the action.
I need assistance with sending bulk email.
This is this scanario.
A dropdown contains the categories of emails to be fetched. The selected (value) is then passed through a function that obtains all the emails per the selected value from db. And the emails passed to the mailer's addAddress method.
The sql query works fine but my headers show only the selected value from the network session and not all the returned emails. I am including both php codes and the ajax codes and also the response headers.
PHP block
$accountid = $_POST['accountid'];
$selectedstatus = $_POST['bulkrecipients']; //From dropdown
$emailtype = $_POST['emailtype'];
$subject = sanitize_text($_POST['bulksubject']);
$message = sanitize_text($_POST['bulkmessage']);
//Pass recipientemails to function and extract individual emails.
$getemails = getAllEmailsFromStatus($selectedstatus , $_SESSION['username']);
$name = 'Tester';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPKeepAlive = true;
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = "";
$mail->Password = '';
$mail->Port = 465;
$mail->SMTPSecure = "ssl";
$mail->isHTML(true);
$mail->setFrom('testproject222', $name);
$mail->Subject = ("$subject");
$mail->Body = $message;
foreach ($getemails as $row) {
try {
$mail->addAddress($row['email']);
} catch (Exception $ex) {
echo 'Invalid address skipped: ' . htmlspecialchars($row['email']) . '<br>';
continue;
}
try {
if ($mail->send()) {
$status = "success";
$response = "Email is sent";
//Save the contact details to db.
saveAllEmployerEmails($accountid , $subject, emailtype, $message );
} else {
$status = "failed";
$response = 'Something is wrong ' . $mail->ErrorInfo;
}
exit(json_encode(array("status" => $status, "response" => $response)));
} catch (Exception $ex) {
echo 'Mailer Error (' . htmlspecialchars($row['email']) . ') ' . $mail->ErrorInfo . '<br>';
$mail->getSMTPInstance()->reset();
}
$mail->clearAddresses();
$mail->clearAttachments();
}
Ajax
function sendBulk() {
var url = "./inc/emailjobs.php";
var accountid = $("#accountid");
var emailtype = $("#emailtype");
var recipientemails = $("#bulkrecipients");
var bulksubject = $("#bulksubject");
var bulkmessage = $('#' + 'bulkmessage').html( tinymce.get('bulkmessage').getContent() );
if (isNotEmpty(recipientemails) /*&& isNotEmptyTextArea("bulkmessage")*/) {
$.ajax({
url: url,
method: 'POST',
cache: false,
dataType: 'json',
beforeSend: function () {
$('#bulksendbtn').text("Sending...");
},
data: {
accountid: accountid.val(),
emailtype: emailtype.val(),
bulksubject: bulksubject.val(),
bulkrecipients: recipientemails.val(),
bulkmessage: bulkmessage.val()
}
, success: function (response) {
$('#bulkemailForm')[0].reset();
$('.bulksendmessage').text("Emails Sent.");
$('#bulksendbtn').text("Sent");
},
});
}
}
Response Form header data
accountid: 2
emailtype: bulk
bulksubject: Test
bulkrecipients: shortlisted
bulkmessage: <p>Testing... </p>
Instead of the 'shortlisted' for bulkrecipients, I expect the email addresses. I was hoping to see 2 returned emails. The 'shortlisted' is supposed to be used to obtain the emails for that category (shortlisted).
Your code looks generally correct, but this is confusing:
$mail->setFrom('Test', $name);
//$mail->From = ("$email");
$email isn't defined, and Test is not a valid from address. I have a suspicion you're trying to use an arbitrary user-submitted email address as the from address. That will not work with Gmail because Gmail does not allow setting arbitrary from addresses; it will only let you send as the account owner (what you put in Username), or aliases that you preset in gmail settings. If you try to use anything else, it will simply ignore it and use your account address instead. Is this what you meant by "only the selected value from the network session"?
It's entirely reasonable for gmail to do this since almost by definition anything other than your account address is likely to be forgery, and nobody likes that.
If you want to send email where replies will go to a user-submitted address, use your own address in the from address, and use the user-submitted address as a reply-to. See the contact form example provided with PHPMailer for how to do that.
I am coding on a system where the admin should be able to click a button and send a mail to all users. When i click the a href and redirect with type = 2 it sends the mail to all accounts but the content which is supposed to be dynamic just returns the email of the last user in the array.
<?php
include "core/init.php";
error_reporting(E_ALL);
date_default_timezone_set('Etc/UTC');
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 0;
$mail->Debugoutput = 'html';
$mail->Host = 'smtprotocl';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "mymail#mail.dk";
$mail->Password = "password";
$mail->CharSet = 'UTF-8';
$mail->setFrom('mymail#mail.dk', 'nameofmailholder');
if ($_GET["type"]) {
if ($_GET["type"] == 2){
$confirmede = 0;
$getVendorc = $db->prepare("SELECT * FROM db");
$getVendorc->execute();
$vresultc = $getVendorc->get_result();
$getVendorc->store_result();
while ($rowing = $vresultc->fetch_assoc()) {
$removeSpace = explode(" ", decrypt($rowing["email"]));
$Uemail = implode("+", $removeSpace);
$mail->addReplyTo($Uemail);
$mail->addAddress($Uemail);
}
$mail->isHTML(true);
$mail->Subject = 'welcome';
$mail->Body = '<button >Bekræft email</button>';
} else {
urlLocation("index");
}
}
$mail->AltBody = 'aa';
if($mail->send()) {
urlLocation("../../index");
}?>
Either create the email (using PHPMailer functions) and send it INSIDE the loop (which is what you should do), or do the following if you want to send one email to all recipients at once (without revealing emails to anyone, because it's BCC). I don't recommend this, but I suppose it could work.
$mail->addAddress("fake#address.com");
$mail->addBCC($email1, $email2, $email3, $email4);
That should work for sending the same email to multiple recipients, in one email without revealing all of the emails to everyone.
Personally, I use wuMail... It makes using PHPMailer a lot easier, especially with SMTP. Here's my setup, with login details changed obviously... I'll explain how it works below, but you would need to download wuMail (link at bottom) so that the files (for PHPMailer) are referenced correctly by config.php & wuMail.php... The code blocks below are references, but can't be used standalone without the rest of the wuMail download.
The first thing that happens is that we set the system defaults... These are used in case certain email parameters are not supplied to wuMail(). This is a fail safe, in case you want a default to address in case part of the system attempts to use wuMail() without supplying to address.. This would let you discover those types of bugs quickly.
The following is the code in config.php... You require config.php in any file that you want to use wuMail() function in (to send mail). Config will set the settings in advance & then bring in the wuMail.php file itself. So don't include the wuMail.php file, just config.php!
<?php
/*
NOTE: These settings have been prepared by
WUBUR.COM / WUBUR LLC / BILLY LOWERY / WILL PASSMORE
*/
# DO NOT REMOVE:
$wuMail_Config = new stdClass();
//SENDER CONFIG SETTINGS - YOU CAN CHANGE THESE:
// ----> Note: This current configuration has a form sending to the same address each time
// ----> This could obviously be adapted to allow for emails being sent elsewhere
$wuMail_Config->SiteName = 'Wubur.com';
//SERVER CONFIG SETTINGS - YOU CAN CHANGE THESE:
$wuMail_Config->isSMTP = true; // Set mailer to use SMTP (TRUE / FALSE)
$wuMail_Config->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$wuMail_Config->SMTPAuth = true; // Enable SMTP authentication (TRUE / FALSE)
$wuMail_Config->AuthType = 'LOGIN'; // Authentification type... ex: PLAIN, LOGIN
$wuMail_Config->Username = 'USERNAME#gmail.com'; // Only blank for GoDaddy's servers
$wuMail_Config->Password = 'PASSWORD'; // Only blank for GoDaddy's servers
$wuMail_Config->SMTPSecure = 'ssl'; // ('tls', 'ssl' or false)
$wuMail_Config->Port = 465; // TCP port to connect to
$wuMail_Config->Exceptions = true; // true/false, if Exceptions enabled
$wuMail_Config->SMTPDebug = 0; // Enable verbose debug output ~~ must be 0 in production environment
//MESSAGE CONFIG SETTINGS - YOU CAN CHANGE THESE:
$wuMail_Config->DefaultToAddress = 'to#email.com';
$wuMail_Config->DefaultToName = 'To Name';
$wuMail_Config->DefaultCC = false; // no default CC
$wuMail_Config->DefaultBCC = false; // no default BCC
$wuMail_Config->DefaultFromAddress = 'from#email.com';
$wuMail_Config->DefaultFromName = 'From Name';
$wuMail_Config->DefaultReplyAddress = 'replyaddress#email.com';
$wuMail_Config->DefaultReplyName = 'Reply Name';
$wuMail_Config->DefaultSubject = 'Default Subject';
# MESSAGE / HTML VERSION CONFIG SETTINGS - YOU CAN CHANGE THESE. BE CAREFUL:
$wuMail_Config->DefaultMessage = 'Default Message (Message Not Supplied)';
$wuMail_Config->ForceHTML = true; // (recommended: true)
// If set to TRUE, and no HTML version of message is supplied to wuMail function, use the HTML template below...Otherwise use HTML supplied to wuMail function if it is supplied.
// If set to FALSE, and no HTML version of message is supplied to wuMail function, simply display a non-HTML message to recipient. If HTML version is supplied, HTML version will be used instead of template
# DefaultHTML: Simply use {!messageInsert!} to insert the regular non-HTML message into the template. {!siteNameInsert!} will insert the config site name.
$wuMail_Config->DefaultHTML = '
<div>
<center><img style="width:350px; height:auto; margin-bottom:25px;" src="site.com/logo.png" alt="Site Name" /></center>
<div style="width:100%; color:white; background-color:#c02026; font-weight:500; padding:10px;">Important Information</div>
<div style="width:100%; padding:25px; color:black; background-color:#f2f2f2;">
{!messageInsert!}
</div>
</div>
';
# NOTE: The 'HTML' key in the options data array for wuMail can be a template with {!messageInsert!} or {!siteNameInsert!} as variables!
// PHPMailer Path Settings:
$wuMail_Path = ""; // path from root dir for site access
// DO NOT REMOVE:
require $wuMail_Path . "wuMail.php";
?>
The URL & logo image in the template should obviously be updated... This is the default template if someone supplies an email message without the HTML version. This is so every email can use HTML templates when allowed, even if developers don't properly use one in the first place :) System settings for the win!
Next we have wuMail.php itself...
<?php
/*
NOTE: These settings have been prepared by
WUBUR.COM / WUBUR LLC / BILLY LOWERY / WILL PASSMORE
*/
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require $wuMail_Path . 'src/Exception.php';
require $wuMail_Path . 'src/PHPMailer.php';
require $wuMail_Path . 'src/SMTP.php';
function wuMail($data, $multi = false){
global $wuMail_Config;
if(!is_array($data)){
$useDefaults = true;
} else {
$useDefaults = false;
}
$mailSettings = array(
"TOADDRESS" => $wuMail_Config->DefaultToAddress,
"TONAME" => $wuMail_Config->DefaultToName,
"CC" => $wuMail_Config->DefaultCC,
"BCC" => $wuMail_Config->DefaultBCC,
"SUBJECT" => $wuMail_Config->DefaultSubject,
"MESSAGE" => $wuMail_Config->DefaultMessage,
"HTML" => $wuMail_Config->DefaultHTML,
"FROMADDRESS" => $wuMail_Config->DefaultFromAddress,
"FROMNAME" => $wuMail_Config->DefaultFromName,
"REPLYADDRESS" => $wuMail_Config->DefaultReplyAddress,
"REPLYNAME" => $wuMail_Config->DefaultReplyName
);
# NOTES: THE FOLLOWING CAN BE ARRAYS: ToAddress, ToName (arr key must match ToAddress arr), CC, BCC
# IN FUTURE, YOU CAN LINE UP EMAILS TO SEND SEPARATELY BY SIMPLY MAKING MULTIDIMENSIONAL ARRAY OF DATA, AND SETTING PARAM 2 (MULTI) EQUAL TO TRUE IN WUMAIL
if($useDefaults !== true){
$submittedOpts = array();
foreach($data as $submittedOption => $submittedValue){
$submittedOptionUPPER = strtoupper($submittedOption);
$submittedOpts[] = $submittedOptionUPPER;
if(isset($mailSettings[$submittedOptionUPPER])){
$mailSettings[$submittedOptionUPPER] = $data[$submittedOption];
} else {
echo "ERROR: SUBMITTED MAIL OPTION NOT ACCEPTED";
}
}
if(($mailSettings['TOADDRESS'] !== $wuMail_Config->DefaultToAddress) && !in_array('TONAME', $submittedOpts)){ # To address supplied, but no to name supplied
# do not use a toName...
$mailSettings['TONAME'] = false;
}
if(($mailSettings['FROMADDRESS'] !== $wuMail_Config->DefaultFromAddress) && !in_array('FROMNAME', $submittedOpts)){ # From address supplied, but no fromname supplied
$mailSettings['FROMNAME'] = false;
# do not use fromname below, because the supplied from address differs from the default in settings
}
if(($mailSettings['REPLYADDRESS'] !== $wuMail_Config->DefaultFromAddress) && !in_array('REPLYNAME', $submittedOpts)){ # Reply address supplied, but no replyname supplied
$mailSettings['REPLYNAME'] = false;
# do not use replyname below, because the supplied reply address differs from the default in settings
}
} # useDefaults !== true
$mail = new PHPMailer($wuMail_Config->Exceptions);
try {
//Server Settings (from PHPMailer/config.php) - Change in config.php file, not here!
$mail->SMTPDebug = $wuMail_Config->SMTPDebug;
if($wuMail_Config->isSMTP === true){ $mail->isSMTP(); }
$mail->Host = $wuMail_Config->Host;
$mail->SMTPAuth = $wuMail_Config->SMTPAuth;
$mail->AuthType = $wuMail_Config->AuthType;
$mail->Username = $wuMail_Config->Username;
$mail->Password = $wuMail_Config->Password;
$mail->SMTPSecure = $wuMail_Config->SMTPSecure;
$mail->Port = $wuMail_Config->Port;
//Recipients
if($mailSettings['FROMNAME'] !== false){
$mail->setFrom($mailSettings['FROMADDRESS'], $mailSettings['FROMNAME']);
} else {
$mail->setFrom($mailSettings['FROMADDRESS']);
}
if($mailSettings['TONAME'] !== false){
$mail->addAddress($mailSettings['TOADDRESS'], $mailSettings['TONAME']);
} else {
$mail->addAddress($mailSettings['TOADDRESS']);
}
if($mailSettings['REPLYNAME'] !== false){
$mail->addReplyTo($mailSettings['REPLYADDRESS'], $mailSettings['REPLYNAME']);
} else {
$mail->addReplyTo($mailSettings['REPLYADDRESS']);
}
if($mailSettings['REPLYNAME'] !== false){
$mail->addReplyTo($mailSettings['REPLYADDRESS'], $mailSettings['REPLYNAME']);
} else {
$mail->addReplyTo($mailSettings['REPLYADDRESS']);
}
if($mailSettings['CC'] !== false){
$mail->addCC($mailSettings['CC']);
}
if($mailSettings['BCC'] !== false){
$mail->addCC($mailSettings['BCC']);
}
//Attachments
#$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
#$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
if($wuMail_Config->ForceHTML !== true && !in_array("HTML", $submittedOpts)){ # ForceHTML is not enforced, and HTML not submitted.... Use plain text message:
$mailSettings['HTML'] = $mailSettings['MESSAGE'];
$mail->isHTML(false);
} else if($wuMail_Config->ForceHTML === true && !in_array("HTML", $submittedOpts)){ # ForceHTML is true, and wuMail received no HTML template to use: ... use default:
$templateVarFind = array("{!messageInsert!}", "{!siteNameInsert!}");
$templateVars = array($mailSettings['MESSAGE'], $wuMail_Config->SiteName);
$mailSettings['HTML'] = str_replace($templateVarFind, $templateVars, $mailSettings['HTML']); // insert variables into default wuMail HTML template
$mail->isHTML(true);
} else {
$mail->isHTML(true);
}
$mail->Subject = $mailSettings['SUBJECT'];
if($mailSettings['HTML'] == $mailSettings['MESSAGE']){
$mail->Body = $mailSettings['MESSAGE'];
} else {
$mail->Body = $mailSettings['HTML'];
$mail->AltBody = $mailSettings['MESSAGE'];
}
$mail->send();
return true;
} catch (Exception $e) {
return 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
} // wuMail end
?>
Finally, after all of this is setup in config.php and wuMail.php, we can begin to use the wuMail() function
require_once "wuMail/config.php";
$mailData = array(
"TOADDRESS" => "userToSendTo#email.com",
"TONAME" => "First Name",
"SUBJECT" => "Registration",
"MESSAGE" => "Hello this is a message",
"HTML" => "Hello this is a <strong>message</strong>",
"FROMADDRESS" => "from#website.com",
"FROMNAME" => "Admin Mail",
"REPLYADDRESS" => "donotreply#email.com"
);
if(wuMail($mailData) === true){
// mail sent
} else {
// mail not successful, change SMTPDebug to = 4 in config.php to bug test
}
As you can see, not all parameters have to be supplied...In the $mailData array you can supply:
$mailSettings = array(
"TOADDRESS" => $wuMail_Config->DefaultToAddress,
"TONAME" => $wuMail_Config->DefaultToName,
"CC" => $wuMail_Config->DefaultCC,
"BCC" => $wuMail_Config->DefaultBCC,
"SUBJECT" => $wuMail_Config->DefaultSubject,
"MESSAGE" => $wuMail_Config->DefaultMessage,
"HTML" => $wuMail_Config->DefaultHTML,
"FROMADDRESS" => $wuMail_Config->DefaultFromAddress,
"FROMNAME" => $wuMail_Config->DefaultFromName,
"REPLYADDRESS" => $wuMail_Config->DefaultReplyAddress,
"REPLYNAME" => $wuMail_Config->DefaultReplyName
);
As you can see, there are quite a few custom parameters you can enter into wuMail($data) when you want to send mail. If you leave any out, it defaults to the settings in config.php for that specific setting! The reply address/name & to address/name & from name/address all are dynamic so that if you supply a custom address (but no name), it will not mismatch the custom email with the default name. It will simply send it with that information as blank.
You can download wuMail if you want it at:
http://nerdi.org/stackoverflow/wuMail.zip
wuMail comes with PHPMailer packaged in and is 100% free... obviously :)
I'm newbie mobile developer, I'm using phonegap as my framework also I'm using firebug to ease me looking for the error / bug that I've got.
I got this error (that I've got on firebug) :
Cross-Origin Request Blocked: The Same Origin Policy disallows.....
This is my code (on server side, because maybe the culprit is the phpmailer and the ajax) :
PHPMailer :
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With");
header("Content-Type: text/html; charset=UTF-8");
include 'db_connect.php';
$applicantEmail = $_POST['PHPRequestor'];
$forgottenPass = '';
//for checking email
$q = "SELECT * FROM user WHERE email = '".$applicantEmail."'";
$result = mysqli_query($con, $q);
if ($result->num_rows == 0) {
echo "no email";
} else if ($result->num_rows == 1) {
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$forgottenPass = $row["pw"];
}
require_once ('class_email/PHPMailerAutoload.php'); //include library phpmailer using auto load
/*
require_once 'class_email/class.phpmailer.php';
require_once 'class_email/class.smtp.php';
*/
$mail = new PHPMailer();
$body =
"<body style='margin: 5px;'>
<br/>
<strong> 'Forgot Password' </strong> :
<br/>
<div style='width: 320px; border:#000000 solid 2px;'>
Your pass : <strong> ".$forgottenPass." </strong> <br/>
</div>
<br/>
Thanks
<br/>
</body>";
$body = eregi_replace("[\]",'',$body);
$mail->IsSMTP(); //Using SMTP
//Activated debug SMTP to see http response
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
//$mail->SMTPDebug = 2;
$mail->SMTPAuth = true; //Authentication
$mail->SMTPSecure = "tls";
// sets the prefix to the
$mail->Host = "smtp.gmail.com"; //Set GMAIL as the SMTP
$mail->Port = 587; //Set the SMTP port for the GMAIL server
$mail->Username = "myemail#email.com"; //Email
$mail->Password = "thepassword"; //Password
//This will add 'Your Name' to the from address, so that the recipient will know the name of the person who sent the e-mail.
$mail->SetFrom("myemail#email.com", "Request Forgot Password");
$mail->AddReplyTo("myemail#email.com", "Request Forgot Password");
$mail->Subject = "Request Forgot Password', user : ".$applicantEmail;
$mail->MsgHTML($body);
$address = "targetemail#email.com"; //target email
$mail->AddAddress($address, "'Permintaan Lupa kata sandi'");
if($mail->Send()) {
echo "success";
} else {
echo "Oops, Mailer Error: " . $mail->ErrorInfo;
exit;
}
}
$con->close();
?>
Ajax (using jquery)
function sendForgotPassword(FPEmail) {
var requestor = FPEmail;
//create form_data for post data on ajax PHP
var form_data = new FormData();
form_data.append("PHPRequestor", requestor);
$.ajax ({
type: "POST",
url: to_phpSide,
data: form_data,
contentType : false,
processData : false,
beforeSend: function() {
loadingPageW(1);
},
success: function(data){
if (data == 'success') {
//when success
} else if (data == 'no email') {
//when no email
} else {
//when error or something else occured
}
}, //for error message
error: function (xhr, errorStats, errorMsg) {
alert("error: "+xhr.errorStats+" , "+errorMsg);
},
complete: function() {
loadingPageW(2);
}
});
};
I already tried in localhost and work well.
But when I trying on hosting, I've got error (on top).
I'm really curious, if the error because of my page trying to request something that cross domain,
then why on the other pages (that I using same method, but without phpmailer) work nice on hosting?
Is there something error? Or method that I miss?
FYI :
I already check about SMTP (phpmailer) support on my hosting and that's support well.
I'm not place the html page in hosting, I just place the .php in hosting
Also I already try : How to specify the SMTP server in PHPMailer?
But still not a chance.
Thanks,
Any help would be appreciate :)
-Edit :
On my firebug (console) there's no error that I got, I already activated $mail->SMTPDebug = 2;, but I couldn't see the error or something else, the response is just empty (nothing there)
I just see
Cross-Origin Request Blocked: The Same Origin Policy disallows.....
-Edit 2 :
By the request #synchro about the URL that causing the error, below is the full error :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http:// myhost/www/myphp. This can be fixed by
moving the resource to the same domain or enabling CORS.
note :
myhost is refer to page that I used for hosting.
myphp is the .php file that contain code above (PHPMailer code)
If you serve your page from http://localhost/index.php and it talks to http://somewhereelse/index.php, that's cross-origin because the domains do not match. You can solve that in several ways:
Set access-control headers as others have described
Proxy the request on your own server so it doesn't appear cross-origin to the browser.
Do whatever it is that the target script does on your own server
The last of these is the simplest.
Also it looks like you're using an old version of PHPMailer and have based your code on an old example. Get the latest here, and look at the examples and wiki.
Try using this code in your PHPMailer:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
I have a script that sends e-mails using phpmailer() with an attached image that it's also displayed in the e-mail body. The receivers that use Outlook or some mobile clients have reported that they have issues viewing the image in the e-mail body.
I've tried to check the way thunderbird attaches the signature. From what I understood the image is linked by it's attachment id but doesn't appear as attachment(I'm not looking for this exact behavior, it can still be as attachment but really need it to be displayed in outlook and mobile clients).
So my question is how should I change my script so that my image is attached to the email the same way thunderbird attaches the signature, or is there a standard, or best practice in doing this?
Edit: code used in sending email script:
$subject = 'Subject - ';
$emails = get_emails()
foreach ($emails as $email) {
define("PHPMAILER",0);
$message = $content;
$path = 'xxx';
require_once ($path);
$mailer = new PHPMailer();
$mailer->SMTPDebug = true;
$mailer->IsSMTP();
$mailer->Host = 'xxx';
$mailer->SMTPAuth = true;
$mailer->SMTPSecure = 'tls';
$mailer->Username = 'xxx';
$mailer->Password = 'xxx';
$mailer->FromName = 'xxx';
$mailer->From = 'xxx';
$mailer->AddAddress($email,"xxx");
$mailer->Subject = $subject;
$mailer->IsHTML(true);
//get the images that needs to be embedded
$embeds = get_images($firma_id,0);
if ($embeds == 0) {echo "No embeds";} else {
foreach ($embeds as $key => $value) {
$mailer->AddEmbeddedImage($value,"img".$key,"grafic_".$key.".png");
}
$mailer->MsgHTML($message);
if (!$mailer->Send()) {
exit;
}
}
}
and the content looks like this:
<td style='font-family: Arial; font-size: 12px;'>
<img style='margin-right: 10px;' src='cid:img".$grafic."' alt='grafic".$grafic."' width='800' align='left'>
</td>
You make a name/identifier for that image attached and call that in image tag at the place(body) you want to show. Code will be like below,
$mail->AddEmbeddedImage('img/image1.jpg', 'logo');
<img src='cid:logo\' />