PHPMailer form input file - php

I'm loosing my mind since yesterday, I'm pretty sure I'm close but...
Well, I have a HTML form with an input type file and I would like get the file submitted attached with the email sent.
Here is my HTML (simplified):
<form enctype="multipart/form-data" id="contact-form-cv" name="contact-form-cv" method="POST" data-name="Contact Form CV">
<div class="form-group">
<div class="controls">
<!-- FILE -->
<input type="hidden" name="MAX_FILE_SIZE" value="300000">
<input type="file" name="cv-file" id="file" class="input-file form-control special-form my-file">
<label for="file" class="btn btn-tertiary js-labelFile">
<span class="js-fileName"><i class="fa fa-upload"></i> Attach CV*</span>
</label>
<!-- Button -->
<button id="cv-valid-form" type="submit" class="btn btn-lg submit">Submit</button>
</div>
</div>
JS
I have a JS file used to display alert messages when the user is filling the form :
$("#contact-form-cv [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var cvuser_file = $('input[name=cv-file]').val();
// Datadata to be sent to server
post_data = {'cvuserFile':cvuser_file};
// Ajax post data to server
$.post('../contact-me-cv.php', post_data, function(response){
// Load json data from server and output message
if(response.type == 'error') {
...
} else {
...
}
}, 'json');
});
PHP
<?php
// Use PHP To Detect An Ajax Request
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
// Exit script for the JSON data
$output = json_encode(
array(
'type'=> 'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(empty($_POST["cvuserFile"])) {
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Please attach your CV'));
die($output);
}
$path = 'upload/' . $_FILES["cvuserFile"]["name"];
move_uploaded_file($_FILES["cvuserFile"]["tmp_name"], $path);
require 'php/class/class.phpmailer.php';
$mail = new PHPMailer();
//Set PHPMailer to use SMTP.
$mail->IsSMTP();
//Set SMTP host name
$mail->Host = 'smtp.gmail.com';
//Set TCP port to connect to
$mail->Port = '587';
//Set the encryption system to use - ssl (deprecated) or tls
$mail->SMTPSecure = 'tls';
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
$mail->isHTML(true);
//Provide username and password yo your google account
$mail->Username = "*****#gmail.com";
$mail->Password = "*******";
$mail->WordWrap = 50;
$mail->From = $_POST["cvuserEmail"];
$mail->FromName = $_POST["cvuserName"];
$mail->setFrom('*****', '**** ****');
$mail->addAddress('*****', 'John Doe');
//Set the subject line
$mail->AddAttachment($path);
$mail->Subject = 'New message from my website!';
$mail->Body = 'Hello' . "\r\n" ;
if(!$mail->send())
{
$output = json_encode(array('type'=>'error', 'text' => '<i class="icon ion-close-round"></i> Oops! Looks like something went wrong, please check your PHP mail configuration.'));
die($output);
unlink($path);
}
else
{
$output = json_encode(array('type'=>'message', 'text' => '<i class="icon ion-checkmark-round"></i> Hello '.$_POST["cvuserName"] .', Your message has been sent, we will get back to you asap !'));
die($output);
}
?>
Is someone able to save my life on that matter?
I'm well receiving the form submission but without the file, I just have an empty file in the email.
Note that I'm working under MAMP for now.
Thanks to this amazing community

You need to use move_uploaded_file (http://php.net/manual/en/function.move-uploaded-file.php) to move your uploaded file in to an accessible location on your file system.
You variable $uploadfile should contain the path to the file.
tempnam (http://php.net/manual/en/function.tempnam.php) only creates a new (empty) file - it doesn't move your uploaded file!

Related

HTML form with PHP does not send from my website to my Gmail account [duplicate]

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.

Maintain formatting when emailing a generated .PDF from a DIV populated using regex

I am unable to generate a PDF from a DIV for emailing to a client while maintaining formatting and variables changed using Regex. Essentially, the PDF file sends as it should attached, but the formatting is messed up (i.e., break space, etc.) and the variables are showing up as {input1}, {input2}, etc, even after being generated.
I've tried multiple other answers on the site I found, including CakePHP and it doesn't work for me.
indexing.html:
For some reason, I can't post HTML code. Basically it's just a Div with the id 'string1' with some text in between which includes {input1}.
*I used regex to replace {input1} with user input.
pdf.php:
require_once 'dompdf/autoload.inc.php';
use Dompdf\Dompdf;
class Pdf extends Dompdf{
public function __construct(){
parent::__construct();
}
}
?>
PHP:
$message = '';
$html= file_get_contents("indexing.html");
$dom = new DOMDocument;
$dom->loadHTML($html);
$div = $dom->getElementById('string1');
$result = $dom->saveHTML($div);
if(isset($_POST["action"]))
{
include('pdf.php');
$file_name = md5(rand()) . '.pdf';
$html_code = '<link rel="stylesheet" href="bootstrap.min.css">';
$pdf = new Pdf();
$pdf->load_html($result);
$pdf->render();
$file = $pdf->output();
file_put_contents($file_name, $file);
require 'class/class.phpmailer.php';
$mail = new PHPMailer();
#$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = ''; // Specify main and backup SMTP servers
#$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ''; // SMTP username
$mail->Password = ''; // SMTP password
#$mail->SMTPSecure = 'SSL'; // Enable SSL
$mail->Port = 587; // TCP port to connect to
$mail->setFrom("", "");
$mail->addAddress("");
$mail->isHTML(true);
$mail->AddAttachment($file_name); //Adds an attachment from a path on the filesystem
$mail->Subject = 'Generate Legal Document'; //Sets the Subject of the message
$mail->Body = 'Please see attached PDF File.'; //An HTML or plain text message body
if($mail->Send()) //Send an Email.
Return true on success or false on error
{
$message = '<label class="text-success">Sent successfully...
</label>';
}
unlink($file_name);
header("Location: indexing.html");
}
The PDF file sends as it should attached, but the formatting is messed up (i.e., break space, etc.) and the variables are showing up as {input1}, {input2}, etc, even after being generated...

I wrote some jquery, html and php code for e-mail form contact but something is wrong

I wrote a code in html, php and jquery in order to be able to make e-mail form on a web site.
However, some problems occurred while testing:
1) problem with validations: in my jquery code, in order to prevent submitting the form before it checks if all the fields are ok, I put ~ e.preventDefault(); ~ insde the jquery code.
Then if I try to submit the form, the script will check if the fields are ok and show errors inside input fields for inputs which are not ok. And, offcourse, it wont send the mail.
But, if I fill all the fields correctly, It won't send the mail either.
2) on the other hand, if I remove the above mentioned ~ e.preventDefault(); ~ code, than the script bypasses field validation checks and sends alerts (for the fields not correctly written) through the Exception alert messages.
3) if all other fields are correctly filled, the script requires the attachment to be sent as well. How to prevent that.
Please help, obviously I made some mistakes inside the code.
My code is:
HTML code:
<form id="kontakt_obrazac" name="kontakt_obrazac" method="POST" action="php/kontakt.php" enctype="multipart/form-data">
<ul>
<li id="ime"><input type="text" name="ime" placeholder="Ime i prezime" id="input_ime" /></li>
<li id="mail"><input type="text" name="mail" placeholder="Mail" id="input_mail" /></li>
<li id="naslov"><input type="text" name="naslov" placeholder="Naslov" id="input_naslov" /></li>
<li id="poruka"><textarea name="poruka" placeholder="Poruka" id="input_poruka"></textarea></li>
<li id="file"><input type="file" name="attachment" value="" id="input_file" /></li>
<li id="posalji"><input type="submit" name="submit_btn" value="Pošalji" class="submit_btn" /></li>
<li id="ponisti"><input type="reset" name="reset_btn" value="Poništi" /></li>
</ul>
</form>
PHP code:
<?php
/* Namespace alias. */
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/* Include the Composer generated autoload.php file. */
require 'C:\xampp\composer\vendor\autoload.php';
/* Create a new PHPMailer object. Passing TRUE to the constructor enables exceptions. */
$mail = new PHPMailer(TRUE);
/* Open try/catch block. */
try
{
if(isset($_POST['submit_btn']))
{
$user_name = $_POST['ime'];
$user_mail = $_POST['mail'];
$subject = $_POST['naslov'];
$message = $_POST['poruka'];
/* Set the mail sender. */
$mail->setFrom($_POST['mail'], $_POST['ime']);
/* Add a recipient. */
$mail->addAddress('nebojsano#gmail.com');
/* Set the subject. */
$mail->Subject = $_POST['naslov'];
/* Set the mail message body. */
$mail->Body = ($_POST['poruka']);
/* SMTP parameters. */
/* Tells PHPMailer to use SMTP. */
$mail->isSMTP();
/* SMTP server address. */
$mail->Host = 'smtp.gmail.com';
/* Use SMTP authentication. */
$mail->SMTPAuth = TRUE;
/* Set the encryption system. */
$mail->SMTPSecure = 'tls';
/* SMTP authentication username. */
$mail->Username = 'nebojsano#gmail.com';
/* SMTP authentication password. */
$mail->Password = 'mmajke';
/* Set the SMTP port. */
$mail->Port = 587;
/* Add an attachment */
$mail->addAttachment($_FILES['attachment']['tmp_name'],$_FILES['attachment']['name']);
/* Set a reply-to address */
$mail->addReplyTo($_POST['mail'], $_POST['ime']);
/* Add CC and BCC recipients */
// $mail->addCC('stones2n#hotmail.com');
/* Enable SMTP debug output. */
//$mail->SMTPDebug = 4;
/* Disable some SSL checks. */
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
/* Finally send the mail. */
if(!$mail->Send())
{
$error = "Mailer Error: " . $mail->ErrorInfo;
echo "Problem in Sending Mail.";
}
else
{
echo "Mail Sent.";
}
}
}
catch (Exception $e)
{
echo $e->errorMessage();
}
catch (\Exception $e)
{
echo $e->getMessage();
}
?>
JQUERY code:
<script>
$(document).ready(function() {
$('#kontakt_obrazac').submit(function(e) {
e.preventDefault();
var ime = $('#input_ime').val();
var mail = $('#input_mail').val();
var naslov = $('#input_naslov').val();
var poruka = $('#input_poruka').val();
var attachment = $('#input_file').val();
$(".error").remove();
if (ime.length < 1) {
$('#input_ime').css({color: "#ff0000"});
$('#input_ime').css({border: "1px solid #ff0000"});
$('#input_ime').attr('placeholder', 'Obavezno polje');
} else {
$('#input_ime').css({color: "#006600"});
$('#input_ime').css({border: "none"});
}
if (mail.length < 1) {
$('#input_mail').css({color: "#ff0000"});
$('#input_mail').css({border: "1px solid #ff0000"});
$('#input_mail').attr('placeholder', 'Obavezno polje');
} else {
var reg_ex = /^[A-Za-z0-9][A-Za-z0-9._%+-]{0,63}#(?:[A-Za-z0-9-]{1,63}\.){1,125}[A-Za-z]{2,63}$/;
var valid_mail = reg_ex.test(mail);
if (valid_mail) {
$('#input_mail').css({color: "#006600"});
$('#input_mail').css({border: "none"});
} else {
$('#input_mail').css({color: "#ff0000"});
$('#input_mail').css({border: "1px solid #ff0000"});
}
}
if (naslov.length < 1) {
$('#input_naslov').css({color: "#ff0000"});
$('#input_naslov').css({border: "1px solid #ff0000"});
$('#input_naslov').attr('placeholder', 'Obavezno polje');
} else {
$('#input_naslov').css({color: "#006600"});
$('#input_naslov').css({border: "none"});
}
if (poruka.length < 1) {
$('#input_poruka').css({color: "#ff0000"});
$('#input_poruka').attr('placeholder', 'Obavezno polje');
} else {
$('#input_poruka').css({color: "green"});
}
});
});
</script>
In your jquery code when you do the preventDefault, at the end of your validation you can return false if the validation failed, and return true to continue the post of the form.
Not sure what you mean with your 3rd problem.

PhpMailer doesn't send Email with .pdf file attached

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.

PHPmailer dynamic data to multiple mails?

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 :)

Categories