I'm trying to send an email with the help of PHPMailer, everything works fine except now I want to have a copy of the send mail in Sent Items.
The website is currently hosted in Bluehost. I tried following the example of PHPMailer - GMail but I'm stuck on which path should I specify.
From the example of PHPMailer - GMail the path for Sent Items is:
{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail
I don't know what path should I specify. Everything works fine in my code, only the path for the sent item is missing.
<?php
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
$username = 'john#mydomain.com';
$password = 'password';
function save_mail( $mail ) {
//path or folder for sent items
$path = "{imap.mydomain.com:993/imap/ssl}[...]/..."; //what exactly is the path for my sent item.
//Tell your server to open an IMAP connection using the same username and password as you used for SMTP
$imapStream = imap_open( $path, $mail->Username, $mail->Password );
$result = imap_append( $imapStream, $path, $mail->getSentMIMEMessage() );
imap_close( $imapStream );
return $result;
}
function send(){
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->Host = 'mail.mydomain.com';
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->SMTPAuth = true;
$mail->Username = $username;
$mail->Password = $password;
$mail->setFrom( $username, 'John Doe' );
$mail->addAddress( 'someone#example.com', 'David Doe' );
$mail->Subject = 'TEST SUBJECT';
$mail->msgHTML('<b>TEST</b>');
$mail->AltBody = 'TEST';
if ( !$mail->send() ) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
if (save_mail($mail)) {
echo "Message saved!";
}
}
}
?>
Thanks to Max for the idea of imap_list function.
This gives me the list of a path for my mail directories.
$host = '{imap.mydomain.com/ssl/novalidate-cert}';
$mail = 'support#mydomain.com';
$pass = 'password';
$mbox = imap_open($host, $mail, $pass, OP_HALFOPEN)
or die("can't connect: " . imap_last_error());
$list = imap_list($mbox, $host, "*");
if (is_array($list)) {
foreach ($list as $val) {
echo imap_utf7_decode($val) . "\n";
}
} else {
echo "imap_list failed: " . imap_last_error() . "\n";
}
imap_close($mbox);
?>
using the {imap.mydomain.com} or {imap.mydomain.com:993/imap/ssl}gives me an error of:
can't connect: Certificate failure for imap.mydomain.com: Server
name does not match certificate: /OU=Domain Control
Validated/OU=Hosted by BlueHost.Com, INC/OU=PositiveSSL
Wildcard/CN=*.bluehost.com
Certificate issue, luckily I found this question and I end up using the following host:
{imap.mydomain.com/ssl/novalidate-cert}
and the path I'm looking to forward the sent mail into sent items is:
{imap.mydomain.com/ssl/novalidate-cert}INBOX.Sent
Related
Please help me out here I have tried possible solutions from former threads but it is not working.
My PHPMailer was working fine in localhost WAMP up until yesterday."SMTP() connection failed" There were no errors in my code, my "extension=php_openssl.dll" is uncommented in the php.ini file. I used port 587 and I even tried 465 but it still doesn't work anymore. My GMAIL allows lesser apps access. No typo errors but then all of a sudden i saw an error in my VScode "intelephense undefined type PHPMailer error 1009" and it highlights lines $mail = new PHPMailer(true); and two more instances of PHPMailer. 3 red lines of that error message in total.
<?php
session_start();
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
require 'vendor/autoload.php';
if ($_POST['admin_create']) {
$name = $_POST['adm_name'];
$email = $_POST['adm_email'];
$pword = $_POST['adm_pass'];
$tel = $_POST['adm_tel'];
$house = $_POST['adm_house'];
// instantiating and passing 'true' enables exceptions
$mail = new PHPMailer(true);
try {
// enable debug output
$mail->SMTPDebug = 4;
// send mail using SMTP
$mail->isSMTP();
// set SMTP server to send through which mail
$mail->Host = 'smtp.gmail.com';
// Enable SMTP authentication
$mail->SMTPAuth = true;
//SMTP Username or Usermail
$mail->Username = 'davolufuwa#gmail.com';
//SMTP Password
$mail->Password = '*********';
//Enabling TLS encryption
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
//TCP Port number to connect to in PHPmailer is 465 and above
$mail->Port = 587;
//Recipients of the code
$mail->setFrom('davolufuwa#gmail.com', 'THE KAKEBOZZ');
// Adding a recipient
$mail->addAddress($email, $name);
//Setting Email format to HTML
$mail->isHTML(true);
$verification_code = substr(number_format(time() * rand(), 0, '',
''), 0, 6);
$mail->Subject = 'Email Verification';
$mail->Body = '<p> Your Verification Code is : <b style="font-
size:30px;">' . $verification_code . '</b>.<br> This code will
expire in 5 minutes.</p>';
$mail->send();
//echo 'Message has been sent';
//encrypt the password
$hashii = password_hash($pword, PASSWORD_DEFAULT);
// connect to the database
$con = mysqli_connect("Localhost", "root", "", "kakeboss");
$sql = "INSERT INTO users (//i didn't put SQL query cos of question
) VALUES
('$name','$email','$tel','$house','$hashii','$verification_code',
NULL)";
$verify = mysqli_query($con, $sql);
if ($verify) {
$timestamp = $_SERVER["REQUEST_TIME"];
$_SESSION['time'] = $timestamp;
echo "PLEASE VERIFY YOUR EMAIL <a href='email_verification.php?
email=" . $email . "'>FROM HERE </a>";
} else {
echo "THAT WAS UNSUCCESSFUL";
}
} catch (Exception $e) {
echo "message couldn't be sent.Mailer Error : {$mail->ErrorInfo}";
}
}
?>
where to put this configuration code
session_start();
require 'phpmailer/class.phpmailer.php';
require 'phpmailer/class.smtp.php';
$result="";
if(isset($_POST['submit'])){
$to = "username";
$from = "username";
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$message = $_POST['msg'];
$msg = 'Full Name : '. $name . " " . "\n\n<br>" . 'Corporate Email : ' . $_POST['email']."\n\n<br>"
. 'Mobile : ' . $_POST['mobile']."\n\n<br>" . 'Company : ' . $_POST['company'] . "\n\n<br>" .
'Subject
: ' . $_POST['subject'] . "\n\n<br>" . 'Message : ' . $_POST['msg'];
$mail = new PHPMailer(true); // Passing `true` enables exceptions
try {
//Server settings
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.rediffmailpro.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'username'; // SMTP username
$mail->Password = 'pass'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption`ssl` also accepted
$mail->Port = 465; // TCP port to connect to
//Recipients
$mail->setFrom($email, $name);
$mail->addAddress('username', 'Seema User'); // Add a recipient
// Name is optional
$mail->addReplyTo('username', 'Seema');
//Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $_post['subject'];
$mail->Body = $msg;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send())
{
$result="Something went wrong......";
}
else{
$result="Your inquiry has been submitted, our team will get in touch with you shortly.";
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo;
}
Normally we include it in that same file or can make another file to control it but wordpress has it's own rules to control it. Can anyone explain how to use phpmailer code in wordpress step by step.
I would be greatful to you if you will help me.
Constructing Forgot UserName Page:
Withing php file is getting hosted under localhost xampp.
Using Gmail email address to send mail to another gmail address with username
No error, just mail is not sent.
I added the following files from Github inside the includes directory.
PHPMailerAutoload.php,
class.phpmailer.php,
class.smtp.php,
class.phpmaileroauth.php,
class.phpmaileroauthgoogle.php,
class.pop3.php
Then inside includes directory created "forgot_username_inc.php" UPDATED
Here is the php code for it
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
require_once 'PHPMailerAutoload.php';
require_once 'class.phpmailer.php';
require_once 'class.smtp.php';
require_once 'class.phpmaileroauth.php';
require_once 'class.phpmaileroauthgoogle.php';
require_once 'class.pop3.php';
$error_msg_username = "";
if (isset($_POST['email'])) {
// Sanitize and validate the data passed in
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg_username .= '<p class="error">The email address you entered
is not valid</p>';
}
$prep_stmt = "SELECT username FROM client WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
// check existing email
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if (!($stmt->num_rows == 1)) {
// If no user with such email
$error_msg_username .= '<p class="error">No User Registered with that Email</p>';
$stmt->close();
}
}
else {
$error_msg_username .= '<p class="error">Database error Line 39</p>';
$stmt->close();
}
if (empty($error_msg_username)) {
if($stmt_username = $mysqli->prepare("SELECT username FROM *** WHERE email = ? LIMIT 1")) {
$stmt_username->bind_param('s', $email);
$stmt_username->execute();
$stmt_username->store_result();
$stmt_username->bind_result($username);
// user found
if ($stmt_username->num_rows == 1) {
// sending mail
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP
authentication
$mail->Port = 587; // set the SMTP port for the GMAIL
server
$mail->Username = 'example#gmail.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption,
'ssl' also accepted
$mail->SMTPDebug = 2;
$mail->From = 'example#gmail.com';
$mail->FromName = 'Admin';
$mail->addAddress($email); // Name is optional
$mail->WordWrap = 50; // Set word wrap to 50
characters
$mail->isHTML(true); // Set email format to
HTML
$mail->Subject = 'User Name Forgot';
$mail->Body = 'Here is your UserName'.$username;
$mail->AltBody = 'Here is your UserName'.$username;
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
//---End of Mail
} // end of userfound
} // end of prepare statement
if (! $stmt_username->execute()) {
header('Location: ../error.php?err=Username Search: FAILED');
exit();
}
$stmt_username->close();
header('Location: ./forgot_username_success.php');
exit();
}
}
?>
Error it shows:
Please log in via your web browser Message could not be sent.Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
What I did: Disable 2-way authentication.Allow less secure apps access.
clear browser cache. I also "unlock CAPTCHA"
https://accounts.google.com/DisplayUnlockCaptcha
Still failed.
UPDATE:
I used GMX instead of gmail & now it sending mails successfully.
I'm a game developer so I do not have any PHP/network/back end web development knowledge. I've been stuck with this problem all week with no luck online. Before PHPMailer, I tried using the mail() function in PHP but I was getting confused with all the .ini files. I found PHPMailer on this site in one of the answers and I have gotten much further. I followed this tutorial https://www.youtube.com/watch?v=FtWD_ZH9lnE&authuser=0 exactly, but the email will not send and debug is not printing out anything. My code always returns false and displays my "can't send email" message.
<?php session_start();
require_once 'PHPMailer/PHPMailerAutoLoad.php';
require_once 'PHPMailer/class.phpmailer.php';
$errors=[];
if(isset($_POST['name'], $_POST['twitterHandle'], $_POST['email'], $_POST['description'])) {
$fields = [
'name' => $_POST['name'],
'twitterHandle' => $_POST['twitterHandle'],
'email' => $_POST['email'],
'description' => $_POST['description']
];
foreach($fields as $field => $data){
if(empty($data)){
$errors[] = 'The ' . $field . ' field is required';
}
}
//mail connection if all fields are ! empty
if(empty($errors)){
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPDebug = 1;
$mail->Host = 'smtp.gmail.com';
$mail->Username = '#gmail.com';
$mail->Password = 'pass';
$mail->SMTPSecure = 'ssl';
$mail->Port = 25;
$mail->isHTML;
$mail->Subject = 'subject';
$mail->Body = 'From: ' . $fields['name'] . ' (' . $fields['email'] . ')<p>' . $fields['description'] . '</p>';
$mail->FromName = 'Contact';
$mail->addReplyTo($fields['email'], $fields['name']);
$mail->addAddress('#gmail.com', 'name');
//send email
if($mail->send()){
header('Location: index.php');
die();
}else{
//cannot send
$errors[] = "Sorry, but I could not process your submission. Please try again.";
}
}
} else{
$errors[] = 'Something went wrong';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: index.php');
?>
I have tried SSL on port 465 and 25 and also TLS on 587. I forwarded 465 and 25 on my network but 587 wont open. IMAP is also enabled on my gmail.
1). Keep using tls.
2). Most probably you've enabled 2Factor Authentication, you need to go to your gmail settings dashboard and allow your app to authenticate with google. I too had the same problem, which only got resolved when I fixed this setting on google.
Also, have a look at this answer :- send email using Gmail SMTP server through PHP Mailer
I am having problem with sending mail using phpmailer. I am a beginner programmer. I am trying to make contact form. My code is as follow(submit.php). Please suggest me.. Thanks in advance .
session_start();
require_once 'libs/phpmail/PHPMailerAutoload.php';
$errors = array();
if(isset($_POST['name'], $_POST['phone'],$_POST['mail'],$_POST['message'])){
$fields = array(
'name' => $_POST['name'],
'phone' => $_POST['phone'],
'email' => $_POST['mail'],
'message' => $_POST['message']
);
foreach ($fields as $field => $data) {
if(empty($data)){
$errors[] = 'The '. $field . ' field is required';
}
}
if(empty($errors)){
$m = new PHPMailer;
$m -> isSMTP();
$m -> SMTPAuth = true;
//$m -> SMTPDebug = 2;
$m -> Host = 'smtp.gmail.com';
$m -> Username = 'xxxx#gmail.com';
$m -> Password = 'xxxx';
$m -> SMTPSecure = 'ssl';
$m -> Port = 465;
$m -> isHTML();
$m -> Subject = 'Contact form submitted';
$m -> Body = 'From: ' . $fields['name']. '('. $fields['phone'] . $fields['email']. ')'.'<p>' .$fields['message'] .'</p> ';
$m -> FromName = 'Contact';
// $m ->addReplyTo($fields['email'], $fields['name']);
$m -> addAddress('ssss#gmail.com', 'xxxxxxxx');
if($m->send()){
header('Location: thanks.php');
die();
}else{
$errors[] = 'Sorry could not send email. Please try again';
}
}
}else{
$errors[] = 'some thing went wrong';
}
$_SESSION['error'] = $errors;
$_SESSION['field'] = $fields;
header('Location: form.php');
My setting phpmailer, everything works
function __construct ($to, $subject, $body) {
date_default_timezone_set('Etc/UTC');
//Create a new PHPMailer instance
$mail = new PHPMailer;
//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 0;
//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';
$mail->CharSet = 'UTF-8';
//Set the hostname of the mail server
$mail->Host = "mail.xxxxxx.com";
//Set the SMTP port number - likely to be 25, 465 or 587
$mail->Port = 25;
//Whether to use SMTP authentication
$mail->SMTPAuth = true;
$mail->AuthType = 'PLAIN';
//Username to use for SMTP authentication
$mail->Username = "xxxx";
//Password to use for SMTP authentication
$mail->Password = "xxxx";
//Set who the message is to be sent from
$mail->setFrom('erp#xxxxxx.com');
//Set an alternative reply-to address
//$mail->addReplyTo('replyto#example.com', 'First Last');
//Set who the message is to be sent to
$mail->addAddress($to);
//Set the subject line
$mail->Subject = $subject;
//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML($body);
//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';
//Attach an image file
//$mail->addAttachment('images/phpmailer_mini.png');
$this->mail = $mail;
}
function SendMail () {
//send the message, check for errors
if (!$this->mail->send()) {
return "Mailer Error: " . $this->mail->ErrorInfo;
} else {
return true;
}
}
// using
$email = $this->request->getPost('email');
$smtp = new \SmtpClient($email, 'Test', $template);
$result = $smtp->SendMail();
Remove
$m -> Subject = 'Contact form submitted';
And try again.
When I remove the subject it worked.