PHPMailer With Shared Hosting (SMTP Transport) - php

I have looked and looked for an answer to this and cannot find anything so If this already has an answer please let me know.
I am using PHPMailer and using SMTP to send emails with files attached.
Here is my Code:
<?php
/**
* SMTP Server Using Yahoo To Upload Files And Submit, Port 465 Using SSL
*/
require_once('PHPMailer/PHPMailerAutoload.php');
define('GUSER', '****#yahoo.com'); // Yahoo username
define('GPWD', '*****'); // Yahoo password
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
// First handle the upload
// Don't trust provided filename - same goes for MIME types
// See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
// Upload handled successfully
// Now create a message
// This should be somewhere in your include_path
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 4; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.mail.yahoo.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->setFrom('****#yahoo.com', 'Sent File');
$mail->addAddress('****#****.com');
$mail->Subject = 'Test File';
$mail->msgHTML("My message body");
// Attach the uploaded file
$mail->addAttachment($uploadfile, $_FILES['userfile']['name']);
if (!$mail->send()) {
$msg = "Mailer Error: " . $mail->ErrorInfo;
} else {
$msg = "Message sent!";
}
} else {
$msg = 'Failed to move file to ' . $uploadfile;
}
}
?>
<?php if (empty($msg)) { ?>
<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
<?php } else {
echo $msg;
} ?>
When I Use This on my local lamp server it works perfectly, However when I use it on my Yahoo Hosting Server, I get this error: SMTP ERROR: Failed to connect to server: Permission denied (13)
Looking into what that error represents, It sounds like the problem and solution has to do with the
httpd_can_sendmail
&
httpd_can_network_connect
Settings. It looks like they need to be activated. Source: http://gistpages.com/2013/09/14/phpmailer_smtp_error_failed_to_connect_to_server_permission_denied_13_fix
My problem is that with Yahoo, I cannot access a terminal to change these settings. Does anyone know of any other way to change these settings without having access to a linux terminal of the hosting server?
Thanks
P.S I would not recommend using yahoo as a website hosting provider EVER to anyone!

Related

PHPMailer won't send an email with attachment which is not already in the uploads folder(Only in production)

I'm making a contact us form on my website, I've used PHPMailer to handle sending the form to my email, everything was working fine on my local host and on a free online host (Heroku) that I was using to test the website. The issue started when the company published the website, the form won't submit when we attach a file which is not already in the uploads folder(or not with the same name of a file in the uploads folder).
Did this problem happen with anyone before, is it an issue with the code or the server or what ?
This is my code :
$path = 'upload/' . $_FILES["personalCV"]["name"];
move_uploaded_file($_FILES["personalCV"]["tmp_name"], $path);
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$mail = new PHPMailer(true);
try {
//Server settings
// $mail->SMTPDebug = 2; // Enable verbose debug output
$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->Username =// <SMTP username>
$mail->Password =// <SMTP password>
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465;
//Recipients
$mail->setFrom(<email>, <AS Website>);
$mail->addAddress(<address>, <name>);
$mail->addAddress(<address>, <name>); // Add a recipient
// Attachments
$mail->AddAttachment($path);
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Job Application From The AS Website ( '.$position.' )';
$msg = '<p> Name : '.$firstName.' '.$lastName.'</p>
<p>Email Address: '.$email.'
</p> <p>Phone Number: '.$phoneNum.'</p>
<p>Position Appling For: '.$position.'</p>
<p> Message: '.$message.'</p>';
$mail->Body = $msg;
$mail->send();
$successMsg = '<div class="alert alert-success" role="alert">
Message successfully sent
</div>';
} catch (Exception $e) {
$failMsg = '<div class="alert alert-danger" role="alert">
Message not successfully sent, please try again
</div>';
}
}
The problem is solved, it was an issue with the server's configuration.

Hostbuddy SMTP mail test, having troubles, could not connect to SMTP host

I am very new to php and im trying to set up a postmaster, I am using Hostbuddy for my hosting site and downloaded their smtp information for my server.
I got these files from them automatically uploaded to my server for testing the smtp:
class.phpmailer.php
class.smtp.php
index.php
web.config
I think i am entering the correct information for the test. but i keep getting a callback that says, "Could not connect to smtp server".
Here is the index.php so you guys can see what is going on.
<Center><h2>PHP Test Email Script</h2></center>
<?php
// display form if user has not clicked submit
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>" target="_blank">
<Table align = center>
<tr><td>From Email: <td><input type="text" name="uname"> i.e yourname#yourdomain.com</tr>
<tr><td>Email Password: <td><input type="password" name="pass"></tr>
<tr><td>Host: <td><input type="text" name="host"> i.e Mail.YourDomain.com</tr>
<tr><td>To:<td> <input type="text" name="to"></tr>
<tr><td colspan =2 align = center><input type="submit" name="submit" value="Send Email"></tr>
</table>
</form>
<?php
}
else { // the user has submitted the form
include("class.phpmailer.php"); //you have to upload class files "class.phpmailer.php" and "class.smtp.php"
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = $_POST["host"];
$mail->Username = $_POST["uname"];
$mail->Password = $_POST["pass"];
$mail->From = $_POST["uname"];
$mail->FromName = "demouser";
$mail->AddAddress($_POST["to"],"test");
$mail->Subject = "This is the subject";
$mail->Body = "This is a sample message using SMTP authentication";
$mail->WordWrap = 50;
$mail->IsHTML(true);
$str1= "gmail.com";
$str2=strtolower($_POST["uname"]);
If(strstr($str2,$str1))
{
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
echo "<br><br> * Please double check the user name and password to confirm that both of them are correct. <br><br>";
echo "* If you are the first time to use gmail smtp to send email, please refer to this link :http://www.smarterasp.net/support/kb/a1546/send-email-from-gmail-with-smtp-authentication-but-got-5_5_1-authentication-required-error.aspx?KBSearchID=137388";
}
else {
echo "Message has been sent";
}
}
else{
$mail->Port = 25;
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
echo "<br><BR>* Please double check the user name and password to confirm that both of them are correct. <br>";
}
else {
echo "Message has been sent";
}
}
}
?>
Any info would be great, thanks in advance!
You need to add the true smtp gmail so you can add :
smtp-relay.gmail.com smtp.gmail.com aspmx.l.google.com
Setting requirement
Options : port 25, 465 ou 587
Protocoles SSL/TLS (Secure Socket Layer/Transport Layer Security)
Port 465 (SSL require).
Port 587 (TLS require).
Adresses dynamic IP allowed.
Port 25.
TLS no require.
Adresses dynamic IP allowed.
Looks like i had it set up correctly, it just took a few hours for hostbuddy to get the smtp server set up. Works great now :) thanks for the suggestions!

delete query to send a mail depending on field value

I have a delete query below from a php page where the user types in an extension number and the entry is deleted from the database.
Name,Email,Extension,Phone,Department the whole line is deleted by entering the extension number of the database member.
Now I have phpmailer installed and working for this, it is sending a mail to IT#sadsa.com but I am trying to make it also send the mail to another address before the member is deleted from the database depending on the department they are in.
Eg. if they are in Sales department then the email must be sent to sales#sadsa.com and IT#sada.com, if they are in the Admin Department then the mail must be sent to Admin#sadsa.com and IT#asdas.com.
My current code below :
delete.php (the php page where the user enters the extension number to delete)
<?php
require ("database.php");
session_start();
if (!isset($_SESSION['CheckLogin'])) { header("Location: login.php"); }
$this_user_ext =$_REQUEST['extension'];
// sending query
mysql_query("DELETE FROM users WHERE extension = '$this_user_ext'")
or die(mysql_error());
if($_POST['action']) {
include('maildelete.php');
$extension=$_POST['extension'];
header("Location: index.php");
}
?>
<center><form action="" method="post">
Enter 4 Digit Extension Number :<br><input type="text" name="extension"><br><input type="submit" name="action" value="Delete!">
<br> <br>
<h3>
Main Menu
</h3>
</form>
</center>
maildelete.php (this is the script that sends the mail to IT#sad.com)
<?php
$extension = $_POST['extension'];
require 'PHPMailer-master/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // telling the class to use SMTP
$mail->Host = "mail.titan-networks.co.za"; // SMTP server // enables SMTP debug information
$mail->SMTPAutoTLS = false;
$mail->SMTPSecure = false;
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->Host = "mail.titan-networks.co.za"; // sets the SMTP server
$mail->Port = 587; // set the SMTP port for the GMAIL server
$mail->Username = "jurgen#titan-networks.co.za"; // SMTP account username
$mail->Password = "****"; // SMTP account password
$mail->From = "no-reply#alpinemotors.co.za";
$mail->FromName = "Extension List";
$mail->AddAddress('jurgen#titan-networks.co.za', "");
$mail->isHTML(true);
$mail->Subject = 'Extension Deleted';
$mail->Body = "Extension Number " . $extension . " was removed from the Extension List";
if(!$mail->Send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Email Sent Successfully!';
?>

SMTP connect failed - PHPMailer Error on Localhost

I was using PHPMailer latest version and I was able to send emails using it. But now I don't know what had happened? Now I'm not able to send mail using it. It gives me following error -
Mailer Error: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting
I have also checked openssl extension.
Here is my code -
<form method="post" action="mail.php">
<input type="text" placeholder="Enter your email to subscribe" name="emailid" />
<input type="submit" value="Submit" />
</form>
The contents of mail.php file
<?php
$emailSubscr = $_POST['emailid'];
$sub = 'New Subscriber';
$message = $emailSubscr.' has subscribed for newsletter';
require 'phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
//$mail->SMTPDebug = 3;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com'; // SMTP Host Name
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'myusername#gmail.com'; // SMTP username
$mail->Password = 'mypassword'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; // TCP port to connect to
$mail->From = $emailSubscr;
$mail->FromName = 'Subscriber';
$mail->addAddress('me#example.com', 'Rohit Kumar'); // Add a recipient
$mail->addReplyTo($emailSubscr, 'Subscriber');
$mail->Subject = $sub;
$mail->Body = $message;
if(!$mail->send()) {
echo 'Some error occured, please try again later.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Thanks for subscribing our newsletter on your email id.';
}
?>
Thanks Faiz Rasool. My issue is resolved.
can you do this please $mail->SMTPDebug = 3; and post the log – Faiz Rasool
Actually I use Mobile Broadband and its ip changes most of the time. And yesterday, google might have detected me as suspicious login when I tried accessing it with my app.When I login to my gmail account I saw a notice to change my password due to which my app was not able to login to my account.You helped me. When I checked the debug log, there was a message from google saying to login via web browser. I did so, resetted the password, selected the Suspicious login attempt as ME and my issue is resolved..
But the main thing here is, after setting google's option - Allow less secure apps to ON, Google was still blocking my app sometimes. I think the reason behind this (I think) is that my ip changes when I disconnect and reconnect my mobile broadband. And hence, my location changes.
By the way, I'm not using the GMail account anymore for my app.

How to send an email with a excel attachment

i am saving excel in folder in my server(note excel is saving in server),i am trying to sent email with an excel attachment that saved in my server,but i didn't receive an email with the attachment(i.e: i received email without an attachment),below is my code please guide me how to do it.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('/data/data/www/ms/pricelists/newxcelexample.xls');
$my_path ="/data/data/www/ms/pricelists/newxcelexample.xls";
include "class.phpmailer.php"; // include the class file name
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
//$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "mail.xichlomobile.com";
$mail->Port = "25"; // or 587
$mail->IsHTML(true);
$mail->Username = "************";
$mail->Password = "**********";
$mail->SetFrom("**************");
$mail->Subject = Test;
$mail->Body = "Test";
$mail->AddAddress("*********");
$mail->AddAttachment($my_path);
if(!$mail->Send()){
echo "Mailer Error: " . $mail->ErrorInfo;
}
else{
echo "<span style='font-size:45px;color:#000000;'>Message has been sent</span><br><br>";
}
Have you controlled that the file is really present and gets saved correctly? Has the web server the right do read the file (normally readable by the user www-data)?
Perhaps try to supply also the filename to AddAttachment:
$mailer->AddAttachment($my_path, basename($my_path));
// or
$mailer->AddAttachment($my_path, basename($my_path), "quoted-printable", "application/vnd.ms-excel") ;
If you're using a newer version of PHPMailer, you can also use exceptions to see what's happening. Perhaps it isn't preventing the mail from going out but from attaching the file.
try {
// preparing the email just before the mail->Send()
} catch (phpmailerException $e) {
echo $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
echo $e->getMessage(); //Boring error messages from anything else!
}
Try sending another file for once, e.g. a *.txt or *.zip (to check if you have limitations on the file types you can send, which would be unlikely for a excel file).

Categories