PHPMailer attachments issue - php

I am trying to create a program to send emails with PHPMailer and I am having a problem.
I am implementing a simple CRUD with HTML that sends it's content via POST Method to the PHP file that execute the PHPMailer. But the problem is that I want to send a file (for example a Microsoft Word file) via the CRUD and it's not working.
Here is my code...
THE HTML CRUD 👇
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send email</title>
</head>
<body>
<div>
<h1>SEND EMAIL</h1>
<br><br>
<form action="email.php" method="POST" enctype="multipart/form-data">
<div>
<label>Subject</label>
<input type="text" name="subject">
</div>
<div>
<label>Message</label>
<input type="text" name="message">
</div>
<div>
<label>Attach file</label>
<input type="file" name="file">
</div>
<div>
<input type="submit" value="Send">
</div>
</form>
</div>
</body>
</html>
THE PHPMailer implementation 👇
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
$mail = new PHPMailer(true);
try {
$mail->SMTPDebug = 0;
$mail->CharSet = 'UTF-8';
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'myemail#gmail.com';
$mail->Password = 'mypassword';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->setFrom('myemail#gmail.com');
$mail->addAddress('mailreceiver#gmail.com');
$mail->isHTML(true);
$mail->Subject = $_POST['subject'];
$mail->Body = $_POST['message'];
$mail->addAttachment($_FILES['file']); 👈 THIS IS WHAT DONT WORK 🔴
$mail->send();
echo("Email has been send");
} catch (Exception $e) {
echo("Error couldn't send the mail");
}
?>
Everything works perfectly without the implementation of the $mail->addAttachment($_FILES['file']);
But when I try to implement the part to attach a file it seems to be
inaccessible for the PHPMailer
So, ¿How can I fix this? I want to attach a file to the PHPMailer with the HTML CRUD

Related

PHP contact form not getting all information from another php file

I created a simple contact form where variable $result output is not appearing above that form when the form is submitted. Please help me out.This contact form works fine in the same php file but when I try with another php file(in my case,fetch.php),variable $result in h4 tag of index.php shows no output after submitting form.
index.php
<?php
include 'fetch.php';
?>
<!DOCTYPE html>
<!-- -->
<html>
<head>
<meta charset="UTF-8">
<title>PHPMailer Contact Form</title>
<style>
label{
display: block;
}
</style>
</head>
<body>
<h4> <?php echo $result; ?> </h4> <!-- here is the problem -->
<form method="post" action="fetch.php">
<label>Name</label>
<input type="text" name="name"><br>
<label>E-mail</label>
<input type="email" name="email"><br>
<label>Subject</label>
<input type="text" name="subject"><br>
<label>Message</label>
<textarea rows="5" cols="40" name="message"></textarea><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
fetch.php
<?php
/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//These lines must be at the top script
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$result=""; // this is the variable i asked about
if(isset($_POST['submit']))
{
$uname=$_POST['name'];
$uemail=$_POST['email'];
$usub=$_POST['subject'];
$umsg=$_POST['message'];
require 'vendor/autoload.php'; //composer's autoloader
$mail = new PHPMailer; //creat object
//Server settings
$mail->Host = 'smtp.gmail.com'; //SMTP server
$mail->isSMTP(); //set mailer to use smtp
$mail->SMTPAuth = true; //enable authentication
$mail->Username = 'my#gmail.com'; //smtp user name
$mail->Password = 'secrete'; // smtp password
$mail->SMTPSecure = 'tls'; //Enable TLS encryption
$mail->Port = 587; //Tcp port to connect
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'From Form :'.$usub; //subject
$mail->Body= '<h3>'
.'Name :'.$uname
.'<br>E-mail :'.$uemail
.'<br>Message :'.$umsg
. '</h3>';`enter code here`
//Recipients
$mail->setFrom($uemail,$uname);
$mail->addAddress('my#gmail.com', 'to User');
$mail->addReplyTo($uemail,$uname);
if(!$mail->send()) //send mail
{
$result = "Message could not be sent.";
}
else
{
$result ="Thank you ".$uname." for contacting us.";
}
}
You have two options,
1. Use sessions
In fetch.php put this code at the end
$ _SESSION['result'] = $result ;
And then you can access
$_SESSION['result'];
in index.php
In order to initialize sessions put
session_start();
at the top of both files.
2. Url parameter
In fetch.php add this at the end
header('Location: index.php?result='.$result);
Then you can access this url parameter in index.php as follows,
$_GET['result'];
index.php
<?php
if(!session_id()) session_start();
?>
<!DOCTYPE html>
<!-- -->
<html>
<head>
<meta charset="UTF-8">
<title>PHPMailer Contact Form</title>
<style>
label{
display: block;
}
</style>
</head>
<body>
<h4> <?php if(isset($_SESSION['result'])){ echo $_SESSION['result']; $_SESSION['result']=''; } ?> </h4> <!-- here is the problem -->
<form method="post" action="fetch.php">
<label>Name</label>
<input type="text" name="name"><br>
<label>E-mail</label>
<input type="email" name="email"><br>
<label>Subject</label>
<input type="text" name="subject"><br>
<label>Message</label>
<textarea rows="5" cols="40" name="message"></textarea><br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
fetch.php
<?php
/*
* To change this license header, choose License Headers in
Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//These lines must be at the top script
if(!session_id()) session_start();
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$result=""; // this is the variable i asked about
if(isset($_POST['submit']))
{
$uname=$_POST['name'];
$uemail=$_POST['email'];
$usub=$_POST['subject'];
$umsg=$_POST['message'];
require 'vendor/autoload.php'; //composer's autoloader
$mail = new PHPMailer; //creat object
//Server settings
$mail->Host = 'smtp.gmail.com'; //SMTP server
$mail->isSMTP(); //set mailer to use smtp
$mail->SMTPAuth = true; //enable authentication
$mail->Username = 'my#gmail.com'; //smtp user name
$mail->Password = 'secrete'; // smtp password
$mail->SMTPSecure = 'tls'; //Enable TLS encryption
$mail->Port = 587; //Tcp port to connect
//Content
$mail->isHTML(true); //Set email format to HTML
$mail->Subject = 'From Form :'.$usub; //subject
$mail->Body= '<h3>'
.'Name :'.$uname
.'<br>E-mail :'.$uemail
.'<br>Message :'.$umsg
. '</h3>';`enter code here`
//Recipients
$mail->setFrom($uemail,$uname);
$mail->addAddress('my#gmail.com', 'to User');
$mail->addReplyTo($uemail,$uname);
if(!$mail->send()) //send mail
{
$result = "Message could not be sent.";
}
else
{
$result ="Thank you ".$uname." for contacting us.";
}
$_SESSION['result'] = $result;
}
header('Location: index.php');

PHPMailer: Sending Failed

Im trying to make a contact form, I searched alot on the web but didn't found any solution that works.
This is contact-form HTML and PHP:
<?php
if(isset($_POST['submit']))
{
$message=
'Name: '.$_POST['name'].'<br />
Subject: '.$_POST['message'].'<br />
Email: '.$_POST['email'].'
';
require 'class.phpmailer.php';
require 'PHPMailerAutoload.php';
// Instantiate Class
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "tls"; // Connect using a TLS connection
$mail->Host = "smtp.gmail.com"; //Gmail SMTP server address
$mail->Port = 587; //Gmail SMTP port
// Authentication
$mail->Username = '**********#gmail.com'; // Your full Gmail address
$mail->Password = '**********'; // Your Gmail password
$mail->SMTPDebug = 1;
// Compose
$mail->SetFrom($_POST['email'], $_POST['name']);
$mail->AddReplyTo($_POST['email'], $_POST['name']);
$mail->Subject = "New Contact Form Enquiry"; // Subject (which isn't required)
$mail->MsgHTML($message);
// Send To
$mail->AddAddress("*********#gmail.com", "Recipient Name"); // Where to send it - Recipient
$result = $mail->Send(); // Send!
$message = $result ? 'Successfully Sent!' : 'Sending Failed!';
unset($mail);
}
?>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<div style="margin: 100px auto 0;width: 300px;">
<h3>Contact Form</h3>
<form name="form1" id="form1" action="" method="post">
<fieldset>
<input type="text" name="name" placeholder="Full Name" />
<br />
<input type="text" name="message" placeholder="Message" />
<br />
<input type="text" name="email" placeholder="Email" />
<br />
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
<p><?php if(!empty($message)) echo $message; ?></p>
</div>
</body>
</html>
I get this Error.
I have the latest version of PHPMailer, Username and Password are correct.
Can someone please help?

how form data in attachment Word in E-mail

I have two things. I have phpmailer, he sent the content of the form to a E-mailaddress, this works. And I have phpword, he make word file, this also works.
I have a question; how can I get the content of the form the $message (Full name, subject, phone, email and comments) in a Word(docx) file in a Email attachment if you click on the submit button?
With this code you see nothing in the browser, how can I 'mix' phpmailer and phpword?.
Can someone help me?
thanks in advance.
The form code is:
<?php
//phpword
require_once '../PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
$section->addText($message, array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Text.docx');
//phpmailer
if(isset($_POST['submit']))
{
$message=
'Full Name: '.$_POST['fullname'].'<br />
Subject: '.$_POST['subject'].'<br />
Phone: '.$_POST['phone'].'<br />
Email: '.$_POST['emailid'].'<br />
Comments: '.$_POST['comments'].'
';
require "phpmailer/class.phpmailer.php"; //include phpmailer class
// Instantiate Class
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "smtp.gmail.com"; //Gmail SMTP server address
$mail->Port = 465; //Gmail SMTP port
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "test#gmail.com"; // Your full Gmail address
$mail->Password = "secret"; // Your Gmail password
// Compose
$mail->SetFrom($_POST['emailid'], $_POST['fullname']);
$mail->AddReplyTo($_POST['emailid'], $_POST['fullname']);
$mail->Subject = "form from website"; // Subject (which isn't required)
$mail->MsgHTML($message);
// Send To
$mail->AddAddress("test#gmail.com", "form from website"); // Where to send it - Recipient
$result = $mail->Send(); // Send!
$message = $result ? 'Successfully Sent!' : 'Sending Failed!';
unset($mail);
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div style="margin: 100px auto 0;width: 300px;">
<h3>Contact Form</h3>
<form name="form1" id="form1" action="" method="post">
<fieldset>
<input type="text" name="fullname" placeholder="Full Name" required/>
<br />
<input type="text" name="subject" placeholder="Subject" />
<br />
<input type="text" name="phone" placeholder="Phone" />
<br />
<input type="text" name="emailid" placeholder="Email" required/>
<br />
<textarea rows="4" cols="20" name="comments" placeholder="Question/Comments"></textarea>
<br />
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
<p><?php if(!empty($message)) echo $message; ?></p>
</div>
</body>
</html>
So basically you are trying to add the content of the variable $message to the word document BEFORE you even declared it.
Also, you don't define an "action" in your form, so it is just doing nothing when you click the submit button.
Assuming that the rest of your code works, this should do it:
<?php
if(isset($_POST['submit']))
{
//phpword
require_once '../PHPWord.php';
//phpmailer
require "phpmailer/class.phpmailer.php"; //include phpmailer class
$message=
'Full Name: '.$_POST['fullname'].'<br />
Subject: '.$_POST['subject'].'<br />
Phone: '.$_POST['phone'].'<br />
Email: '.$_POST['emailid'].'<br />
Comments: '.$_POST['comments'].'
';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
$section->addText($message, array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Text.docx');
// Instantiate Class
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "smtp.gmail.com"; //Gmail SMTP server address
$mail->Port = 465; //Gmail SMTP port
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "test#gmail.com"; // Your full Gmail address
$mail->Password = "secret"; // Your Gmail password
// Compose
$mail->SetFrom($_POST['emailid'], $_POST['fullname']);
$mail->AddReplyTo($_POST['emailid'], $_POST['fullname']);
$mail->Subject = "form from website"; // Subject (which isn't required)
$mail->MsgHTML($message);
// Send To
$mail->AddAddress("test#gmail.com", "form from website"); // Where to send it - Recipient
$result = $mail->Send(); // Send!
$message = $result ? 'Successfully Sent!' : 'Sending Failed!';
unset($mail);
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div style="margin: 100px auto 0;width: 300px;">
<h3>Contact Form</h3>
<form name="form1" id="form1" action="url.php" method="post">
<fieldset>
<input type="text" name="fullname" placeholder="Full Name" required/>
<br />
<input type="text" name="subject" placeholder="Subject" />
<br />
<input type="text" name="phone" placeholder="Phone" />
<br />
<input type="text" name="emailid" placeholder="Email" required/>
<br />
<textarea rows="4" cols="20" name="comments" placeholder="Question/Comments"></textarea>
<br />
<input type="submit" name="submit" value="Send" />
</fieldset>
</form>
<p><?php if(!empty($message)) echo $message; ?></p>
</div>
</body>
</html>
Remember to replace "url.php" with the real URL of your page.
Regards
EDIT:
In order to be able to attach the Word file with phpmailer and reading the documentation (https://github.com/PHPMailer/PHPMailer/wiki/Tutorial):
The command to attach a local file is simply
$mail->addAttachment($path);, where $path contains the path to the
file you want to send, and can be placed anywhere between $mail = new
PHPMailer; and sending the message. Note that you cannot use a URL for
the path - you may only use local filesystem path. See notes on string
attachments below for how to use remote content.
Translated to your script, this means you have to add the following line:
[...]
$mail->AddAddress("test#gmail.com", "form from website"); // Where to send it - Recipient
$mail->addAttachment("Text.docx"); // <--------------------------
$result = $mail->Send(); // Send!

Bulk Email using form not working

I am trying to send bulk email from gmail using php in which from address,to address and message are set from a form. But it is not working..shows error
Mail.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHPMailer - GMail SMTP test</title>
</head>
<body>
<?php
date_default_timezone_set('Etc/UTC');
require '../Mail/class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "username#gmail.com";
$mail->Password = "passwrd";
$mail->SetFrom("$_POST('from')","$_POST('from_name')");
$mail->AddReplyTo("$_POST('from')","$_POST('from_name')");
$mail->AddAddress("$_POST('to')","$_POST('from_name')");
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->MsgHTML("$_POST('message')");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</body>
</html>
Index.php
<form action="mail.php" method="POST">
<div>
From:
<input type="text" name="from" />
Name:<input type="text" name="from_name" />
</div>
<div>
to:
<input type="text" name="to" />
Name:<input type="text" name="to_name" />
</div>
<div>
Message:
<textarea name="message"></textarea>
</div>
<input type="submit" value ="Submit"/>
</form>
it shows the follwing error:
Invalid address: Array('from')
Invalid address: Array('from')
Invalid address: Array('to')
Mailer Error: You must provide at least one recipient email address.
Someone please help me to solve this problem. I am not getting what the problem is.
Cargo-cult programming:
$mail->SetFrom("$_POST('from')","$_POST('from_name')");
should probably just be
$mail->SetFrom($_POST['from'], $_POST['from_name']);
Note the use of [] instead of (), and the LACK of " quotes around those single values.
You'll have to fix up every line of code in your script where you're doing this sort of bad array referencing.

adding attachment from form while sending mail from gmail via php

i am trying to add atatchment while sending mail from gmail using php. But it shows error...it says Could not access file: hai.jpg
follwing is the code i use
gmail.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHPMailer - GMail SMTP test</title>
</head>
<body>
<?php
access to that
date_default_timezone_set('Etc/UTC');
require '../Mail/class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "name#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "passwrd";
$mail->SetFrom($_POST['from'], $_POST['from_name']);
$mail->AddReplyTo($_POST['from'],$_POST['from_name']);
$mail->AddAddress($_POST['to'],$_POST['to_name']);
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->MsgHTML($_POST['message']);
$mail->AltBody = 'This is a plain-text message body';
$mail->AddAttachment($_POST['attachment'],'application/octet-stream');
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</body>
</html>
index.html
<form action="gmail.php" method="POST">
<div>
From Name:<input type="text" name="from_name" />
From:<input type="text" name="from" />
</div>
<div>
To Name:<input type="text" name="to_name" />
To:<input type="text" name="to" />
</div>
<div>
Message:<textarea name="message"></textarea>
</div>
<div>
Attachment:<input type="file" name="attachment" />
</div>
<input type="submit" value ="Submit"/>
</form>
I dont know what if i am doing the right way here.Can anyone please guide me through this?
I've notice the absence of two itens in your code:
The use of the php $_FILES variable, which stores information about the uploaded files
The use of enctype attribute in your form element, which is required to upload files along with the form.
So, your code must treat this two itens.
Your form will look like this:
<form action="gmail.php" method="POST" enctype="multipart/form-data">
<div>
From Name:<input type="text" name="from_name" />
From:<input type="text" name="from" />
</div>
<div>
To Name:<input type="text" name="to_name" />
To:<input type="text" name="to" />
</div>
<div>
Message:<textarea name="message"></textarea>
</div>
<div>
Attachment:<input type="file" name="attachment" />
</div>
<input type="submit" value ="Submit"/>
</form>
And your code may treat the $_FILES variable:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHPMailer - GMail SMTP test</title>
</head>
<body>
<?php
//access to that
date_default_timezone_set('Etc/UTC');
require '../Mail/class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'html';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "name#gmail.com";
//Password to use for SMTP authentication
$mail->Password = "passwrd";
$mail->SetFrom($_POST['from'], $_POST['from_name']);
$mail->AddReplyTo($_POST['from'],$_POST['from_name']);
$mail->AddAddress($_POST['to'],$_POST['to_name']);
$mail->Subject = 'PHPMailer GMail SMTP test';
$mail->MsgHTML($_POST['message']);
$mail->AltBody = 'This is a plain-text message body';
//Attachs the file only if it was uploaded by http post
if (is_uploaded_file ($_FILES['attachment']['tmp_name'])) {
$mail->AddAttachment($_FILES['attachment']['tmp_name'],$_FILES['attachment']['name'], 'base64',$_FILES['attachment']['type']);
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
</body>
</html>
Its not quite that straight forward uploading a file from the client browser to the server.
Here's a simple tutorial

Categories