PHPMailer not sending Emails on One Host but sends on another Host - php

PHPMailer sends emails on one host but doesn't send on another host using exactly the same code.
I contacted the host and they sent me the following screenshot
The server protects from email, so they indicated that to send the emails from a different host or with any host, I have to use ini_set( 'sendmail_from', 'email#example.com' );. Well, that solution works fine for the normal PHP mail function, mail() but not for the PHPMailer.
Would someone help me figure out how to solve this issue on PHPMailer?
The following is my code, which has been tested on another hosting and works fine only on the current server where no email gets sent despite using ini_set()
require_once('email-sending/PHPMailer/PHPMailer.php');
require_once('email-sending/PHPMailer/Exception.php');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
/*!
*
*
* This class handles the sending and processing of emails
*
* */
class Email{
const BASE_URL = 'http://cryptodegen.co.uk'; // please enter domain name of your website without the trailing slash, e.g https://example.com
const SHORT_DOMAIN = 'cryptodegen.co.uk'; // Enter short domain without https e.g example.com
const SYSTEM_NAME = 'Crypto Degen '; // Website Name
const LOGO_URL = self::BASE_URL . '/email-sending/logo/logo-black1.png'; // your website logo, if blank emails will be sent without logo
const FOOTER_TEXT = 'Crypto Degen, San Francisco CA 94102, This text is editable'; // footer text
const EMAIL_SENDER = 'noreply#cryptodegen.co.uk'; //
const REPLY_TO = 'info#cryptodegen.co.uk'; // senders will reply to
/*!
*
* $to = recepient, $subject = Email Subject, $message = HTML MESSAGE
*
* $ttachements should be array of files url
*
*
* $attachemnet is optional, you can jsut say:
* Email::send( 'catekhui#gmail.com', 'Urgent subject', Hello html email message' );
*
*
* */
static function send( $to, $subject, $message, $attachments = array() ){
try {
ini_set( "sendmail_from", self::EMAIL_SENDER );
$email = new PHPMailer( true );
$email->SetFrom( self::EMAIL_SENDER, self::SHORT_DOMAIN );
$email->Subject = $subject;
$email->Body = get_email_template( $message );
$email->AddAddress( $to );
$email->isHTML(true);
$email->addReplyTo( self::REPLY_TO, '' );
foreach ($attachments as $key => $value) {
// code...
$email->AddAttachment( $value , basename( $value ) );
}
$email->Send();
return true;
} catch( Exception $e ){
?>
<script>
window.onload = function() {
alert("<?php echo $e; ?>");
}
</script>
<?php
}
return false;
}
}

You need to set the envelope sender, which is separate from the from address. Try this:
$mail->Sender = self::EMAIL_SENDER;

Related

PHPmailer send copy to email address in a form

I'm working on editing a site which has been built using some strange Smarty system, template TPL files and a load of JS and PHP.
I have a Classes in PHP files which sends and email to an array of email address from a differnt PHP file.
I'm wanted to add to this array so it sends a copy of the email to the person who filled in the form.
The array of recipents is:
//target email address settings
$this->settings['mailer_address_booknow'] = array('ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'ADDRESS#ADDRESS.com', 'james#bernhardmedia.com');
And the sending PHP file is:
public function SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message ) {
$smartyObj = Configurator::getInstance()->smarty;
$send_message = '';
$send_result = 0;
try {
$mail = new PHPMailer( true );
$mail->IsSMTP( true );
$mail->SMTPDebug = false;
$mail->IsHTML( true );
$mail->Host = Configurator::getInstance()->getSettings( "phpmailer_smtp" );
$mail->ClearAddresses();
for( $x = 0;$x < sizeof($email_address_array);$x++ ){
$mail->AddAddress( trim($email_address_array[$x]) );
}
$smartyObj->assign( 'email_data', $email_data );
$mail->SetFrom( 'info#forexchange.co.uk', 'Forexchange Currency Order');
$mail->Subject = $subject;
$mail->Body = $smartyObj->fetch( $template );
if(!$mail->Send()) {
} else {
$send_result = 1;
}
} catch (phpmailerException $e) {
$send_message = $e->errorMessage(); //Pretty error messages from PHPMailer
} catch (Exception $e) {
$send_message = $e->getMessage(); //Boring error messages from anything else!
}
//echo $send_result;
//exit;
return $send_result;
}
The form is on the home page of this site - http://www.forexchange.co.uk/
Please help, I'm stumped!
Smarty I think refers to the Smarty template Engine for php see here
Append the email address to the array $email_address_array
When you call the method
SendEmail( $email_address_array, $email_data, $subject, $template, &$send_message );
either append the email to that data set ($email_address_array) before you call it or append it inline ( in the call)
Can you show how you call it?
EDIT
If your data is stored in
$this->settings['mailer_address_booknow'];
add that to the call,
SendEmail( $this->settings['mailer_address_booknow'] , $email_data, $subject, $template, &$send_message );
if you need to add to that array then do this before calling it
$this->settings['mailer_address_booknow'] = "ADDED_EMAIL";

Cron job doesn't send email [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I have a cron job set up on my hostgator server that returns a value of 1 (email sent), but doesn't actually send the email. When I call the php file manually in the browser, the email gets sent. It doesn't if run via cron.
Earlier this month, I moved my site from one server on hostgator to another server (on hostgator) so I could get SSL and a dedicated IP address. Since moving the site, the cron jobs work OK except for the part that sends the email (ie, database functions work fine). I've contacted hostgator tech support, but he thinks the problem is in my code.
Thinking that maybe my server info was incorrect, I switched to using smtp.gmail.com and using a gmail account to send the mail, but that didn't work either. Please help!
The cron job is set up like this:
* 7 * * * /opt/php56/bin/php /home/user/public_html/somefolder/sendmailcron.php
(While testing, I changed it to run every 2 minutes: */2 * * * * )
Here's the sendmailcron.php script:
<?php
$now = date("Y-m-d H:i:s");
$msgcontent = [];
$msgcontent['email'] = "recipient#example.com";
$msgcontent['name'] = "Recipient Name";
$msgcontent['textpart'] = "This is the text version of the email body.";
$msgcontent['htmlpart'] = "<p>This is the <strong>HTML</strong> version of the email body.</p>";
$msgcontent['subject'] = "Test email sent at " . $now;
$result = sendMyMail($msgcontent, "HTML");
exit();
function sendMyMail($msgcontent, $format="HTML") {
require_once '/home/user/public_html/somefolder/swiftmailer/lib/swift_required.php';
$result = 0;
$subject = $msgcontent['subject'];
$email = $msgcontent['email'];
if (strlen($email) == 0) {
return 0;
}
$name = $msgcontent['name'];
$emailbody = $msgcontent['textpart'];
$emailpart = $msgcontent['htmlpart'];
switch($format) {
case "TEXT":
$msgformat = 'text/plain';
break;
case "HTML":
$msgformat = 'text/html; charset=UTF-8';
break;
default:
$msgformat = 'text/html';
break;
}
$adminemailaddress = "me#mydomain.com";
$adminemailpwd = 'myadminpwd';
$sendername = 'My Real Name';
$transport = Swift_SmtpTransport::newInstance('mygator1234.hostgator.com', 465, "ssl")
->setUsername($adminemailaddress)
->setPassword($adminemailpwd)
;
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
if($format == "TEXT") {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailbody)
->setContentType($msgformat)
;
}
else {
$message = Swift_Message::newInstance($subject)
->setFrom(array($adminemailaddress => $sendername))
->setTo(array($email => $name))
->setBody($emailpart)
->setContentType($msgformat)
;
}
//This is where we send the email
try {
$result = $mailer->send($message); //returns the number of messages sent
} catch(\Swift_TransportException $e){
$response = $e->getMessage() ;
}
return $result; //will be 1 if success or 0 if fail
}
?>
The return value is always 1, but no email is sent.
Any suggestions would be greatly appreciated!
Your cron job uses a different php.ini configuration file, than your browser uses.
Try running the cron job by disabling safe_mode, like this:
/opt/php56/bin/php -d safe_mode=Off /home/user/public_html/somefolder/sendmailcron.php
And check if the email is now sent.

PHP Direct SMTP Send + Attachment

I'm using xpertmailer to send email direct to the remote SMTP server following an MX lookup. This works really well and works on an old closed source NAS drive running PHP4 and on current PHP5 boxes.
<?php
define('DISPLAY_XPM4_ERRORS', true); // display XPM4 errors
require_once '/path-to/SMTP.php'; // path to 'SMTP.php' file from XPM4 package
$f = 'me#mydomain.net'; // from mail address
$t = 'client#destination.net'; // to mail address
// standard mail message RFC2822
$m = 'From: '.$f."\r\n".
'To: '.$t."\r\n".
'Subject: test'."\r\n".
'Content-Type: text/plain'."\r\n\r\n".
'Text message.';
$h = explode('#', $t); // get client hostname
$c = SMTP::MXconnect($h[1]); // connect to SMTP server (direct) from MX hosts list
$s = SMTP::Send($c, array($t), $m, $f); // send mail
// print result
if ($s) echo 'Sent !';
else print_r($_RESULT);
SMTP::Disconnect($c); // disconnect
?>
I'm now trying to add an attachment to it, but I've no idea how to get an attachment to be included and sent.
Anyone any ideas how I can do this ?
Thanks
Example:
$m = new MAIL;
// attach source
$a = $m->Attach('text message', 'text/plain');
$f = '/path/image.gif';
// attach file '$f', disposition 'inline' and give a name 'photo.gif' with ID value (this ID value can be used in embed HTML images)
$a = $m->Attach(file_get_contents($f), FUNC::mime_type($f), 'photo.gif', null, null, 'inline', MIME::unique());
echo $a ? 'attached' : 'error';

Why is this script sending blank emails without using template in SugarCRM?

This is my code to send emails in SugarCRM CE 6.5.x version,
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid EntryPoint');
require_once('include/SugarPHPMailer.php');
$msg = new SugarPHPMailer();
$emailObj = new Email();
$defaults = $emailObj->getSystemDefaultEmail();
//Setup template
require_once('XTemplate/xtpl.php');
$xtpl = new XTemplate('custom/modules/Users/ChangePassword.html');
//assign recipients email and name
$rcpt_email = 'sohan.tirpude#mphasis.com';
$rcpt_name = 'Sohan';
//Set RECIPIENT's address
$email = $msg->AddAddress($rcpt_email, $rcpt_name);
//Send msg to users
$template_name = 'User';
//Assign values to variables in template
$xtpl->assign('EMAIL_NAME', $rcpt_name);
$xtpl->parse();
//$body = "Hello Sohan, It's been 80 days that you haven't changed your password. Please take some time out to change password first before it expires.";
$msg->From = $defaults['email'];
$msg->FromName = $defaults['name'];
$msg->Body = from_html(trim($xtpl->text($template_name)));
//$msg->Body = $body;
$msg->Subject = 'Change Password Request';
$msg->prepForOutbound();
$msg->AddAddress($email);
$msg->setMailerForSystem();
//Send the message, log if error occurs
if (!$msg->Send()){
$GLOBALS['log']->fatal('Error sending e-mail: ' . $msg->ErrorInfo);
}
?>
Now this script send blanks emails, and when I hardcoded body part then it is takes those message written in body, and sends an email. So, please help me here.

Creating a Craigslist Anonymous Email Forwarding Program

The following program is intended to match incoming email aliases with those in the database, and forward the email to the right address, like Craigslist does.
I am now getting this error:
Error: [1] You must provide at least one recipient email address.
in anon-email.php at line number: sending the email
Here is the code:
$mailboxinfo = imap_mailboxmsginfo($connection);
$messageCount = $mailboxinfo->Nmsgs; //Number of emails in the inbox
for ($MID = 1; $MID <= $messageCount; $MID++)
{
$EmailHeaders = imap_headerinfo($connection, $MID); //Save all of the header information
$Body = imap_qprint(imap_fetchbody($connection, $MID, 1)); //The body of the email to be forwarded
$MessageSentToAllArray = $EmailHeaders->to; //Grab the “TO” header
$MessageSentToAllObject = $MessageSentToAllArray[0];
$MessageSentToMailbox = $MessageSentToAllObject->mailbox ."#". $MessageSentToAllObject->host; //Everything before and after the “#” of the recipient
$MessageSentFromAllArray = $EmailHeaders->from; //Grab the “FROM” header
$MessageSentFromAllObject = $MessageSentFromAllArray[0];
$MessageSentFromMailbox = $MessageSentFromAllObject->mailbox ."#". $MessageSentFromAllObject->host; //Everything before and after the “#” of the sender
$MessageSentFromName = $MessageSentFromAllObject->personal; //The name of the person who sent the email
$toArray = searchRecipient($MessageSentToMailbox); //Find the correct person to send the email to
if($toArray == FALSE) //If the alias they entered doesn’t exist…
{
$bounceback = 'Sorry the email in your message does not appear to be correct';
/* Send a bounceback email */
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain email
$mail -> IsHTML(false); //No HTML
$the_body = wordWrap($bounceback, 70); //Word wrap to 70 characters for formatting
$from_email_address = 'name#domain.com';
$mail->AddReplyTo($from_email_address, "domain.Com");
$mail->SetFrom($from_email_address, "domain.Com");
$address = $MessageSentFromMailbox; //Who we’re sending the email to
$mail->AddAddress($address, $MessageSentFromName);
$mail->Subject = 'Request'; //Subject of the email
$mail->Body = $the_body;
if(!$mail->Send()) //If the mail fails, send to customError
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
else //If the candidate address exists, forward on the email
{
$mail = new PHPMailer(); // defaults to using php “mail()”
$mail -> ContentType = 'text/plain'; //Plain E-mail
$mail -> IsHTML(FALSE); //No HTML
$the_body = wordwrap($Body, 70); //Wordwrap for proper email formatting
$from_email_address = "$MessageSentFromMailbox";
$mail->AddReplyTo($from_email_address);
$mail->SetFrom($from_email_address);
$address = $toArray[1]; //Who we’re sending the email to
$mail->AddAddress($address, $toArray[0]); //The name of the person we’re sending to
$mail->Subject = $EmailHeaders->subject; //Subject of the email
$mail->Body = ($the_body);
if(!$mail->Send()) //If mail fails, go to the custom error
{
customError(1, $mail->ErrorInfo, "anon-email.php", "sending the email");
}
}
/* Mark the email for deletion after processing */
imap_delete($connection, $MID);
}
imap_expunge($connection); // Expunge processes all of the emails marked to be deleted
imap_close($connection);
function searchRecipient() // function to search the database for the real email
{
global $MessageSentToMailbox; // bring in the alias email
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_array($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_array($results, $email_addr); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
function customError($errno, $errstr, $file, $line)
{
error_log("Error: [$errno] $errstr in $file at line number: $line",1, "name#domain.com","From: name#domain.com.com");
die();
}
Here is the first thing I would try:
It would appear that your function searchRecipient isn't being passed a parameter. Rather than use the global keyword, I would define it in your function call. Also, mysql_fetch_array does not pass back an associative array, which is what you are using in your next step. I would change that to mysql_fetch_assoc (it's the same thing essentially). There are also a few other minor syntax corrections in this function. Here are my proposed changes to that function. I think this should fix your problem. Or at least get you moving forward.
function searchRecipient($MessageSentToMailbox) // function to search the database for the real email
{
$email_addr = mysql_query("SELECT email FROM tbl WHERE source='$MessageSentToMailbox'"); // temp store of the real email
$row = mysql_fetch_assoc($email_addr); //making temp store of data for use in program
if(empty($row['email']))
{
return FALSE;
}
else /* Else, return find the person's name and return both in an array */
{
$email_addr = $row['email'];
$results = mysql_query("SELECT * FROM tbl WHERE email = '$email_addr'"); // temp store of both queries from this function
$row = mysql_fetch_assoc($results); //making temp store of data for use in program
$name = $row['author']; // taking the author data and naming its variable
return array($name, $email_addr); // this is the name and the real email address to be used in function call
}
}
You could also combine this into one query and make it a little easier. Here is that solution.
function searchRecipient($MessageSentToMailbox)
{
$results = mysql_query("SELECT email, author FROM tbl WHERE source='$MessageSentToMailbox'");
$row = mysql_fetch_assoc($results);
if(empty($row['email']) || empty($row['author'])) return false;
return array($row['email'], $row['author']);
}

Categories