I have a php script that sends an email with an attachment. When I manually execute the php script below via a web browser, everything works well and the email is sent instantly. However, when I try to execute the php file using a crontab command, the email is not sent. Any idea why this is? The cron command isn't generating any errors...
Further, the email_output.log shows success but the email doesn't come through, as if it is piling up in the outgoing box but never actually sent.
Crontab command:
/Applications/MAMP/bin/php/php5.6.10/bin/php /my/path/emailApp.php > /my/path/email_console.log 2> /my/path/email_error.log
Thanks in advance.
<?php
include_once(__DIR__ . '/mailer/swift_required.php');
$transport = Swift_SmtpTransport::newInstance('mail.myhost.com', 25)
->setUsername('name#myhost.com')
->setPassword('password');
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
$mailTo = Array('testemail#gmail.com');
$subject ="report";
$attach = 'report.pdf';
$message = Swift_Message::newInstance($subject)
->setFrom(array('name#mydomain.com' => 'Bob Dole' ))
->attach(Swift_Attachment::fromPath($attach)->setFilename($attach))
->setTo($mailTo);
$message->setBody("attached",'text/html');
// Send the message
$result = $mailer->send($message);
if($result == 0){
echo 'Error';
} else {
echo 'Success';
}
Related
I have been trying to setup up a system with this functionality:
Send email to my server
Server pipes email to php script
Php script parses email getting subject and body
Get phone number from subject of email and send text with email body
I have found an email parser here: https://github.com/daniele-occhipinti/php-email-parser
I think I have setup it up correctly but I do not know how to test it besides just sending an email. But I cannot see what my script echos at that point. Also when I do send the email I know something is not working because the text does not send via twilio. What am I doing wrong?
Here is the code:
#!/usr/bin/php -q
<?php
require_once '../resources/Twilio/autoload.php';
use Twilio\Rest\Client;
require('config.php');
// Retrieve Email
require_once("../resources/PlancakeEmailParser.php");
$email = "php://stdin";
$emailParser = new PlancakeEmailParser(file_get_contents($email));
$subject = $emailParser->getSubject();
$text = $emailParser->getPlainBody();
$number = preg_replace('/[^0-9]/', '', $subject);
$phone = "+".$number;
// After this I send the message via Twilio
You are piping the input so you probably need to buffer the stream to ensure you have received all the data before you try and process it.
Something like this:
$dataIn = fopen('php://stdin', 'r');
if ($dataIn) {
$email = '';
while($line = fgets($dataIn)) {
$email .= $line;
}
fclose($dataIn);
}
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.
i need to create a custom mailing script in magento in Shell folder. I got the sample script from internet. this script was described as a stand alone script and no template id's are required and this type of script is what I needed and program didn't work for me.Below is the script.
require '../app/Mage.php';
ini_set('display_errors', true);
ini_set('max_execution_time', 3600); // just put a lot of time
ini_set('default_socket_timeout', 3600); // same
set_time_limit(0);
class Mage_Shell_Report
{
public function myfunc()
{
$body = "Hi there, here is some plaintext body content";
$mail = Mage::getModel('core/email');
$mail->setToName('reig');
$mail->setToEmail('rieg.philippe#neuf.fr');
$mail->setBody($body);
$mail->setSubject('The Subject');
$mail->setFromEmail('boutique#infosys.com');
$mail->setFromName("divine");
$mail->setType('text');// You can use 'html' or 'text'
try {
$mail->send();
if($mail->send())
{
$msg = true;
echo "<br>mail sent<br>";
}
else
{
echo "<br>mail not send<br>";
}
Mage::getSingleton('core/session')->addSuccess('Your request has been sent');
}
catch (Exception $e) {
Mage::getSingleton('core/session')->addError('Unable to send.');
$this->_redirect('');
}
echo "<br>end program<br>";
}
}
echo "out-1";
$shell1 = new Mage_Shell_Report();
$shell1->myfunc();
?>
This program shows no error . Though mail function returns success , i am not receiving any mail. i am testing in local using SMTP. Other email's, like order email, customer emails are sent successfully and can be viewed in SMTP mailbox. I browsed through pages and came to know that this issue has something to do with queuing but am not clear about that. Kindly help me out
Since today, many of my php applications can not send email using SwiftMailer and different Mandrill accounts.
I've got this code, and the send function in the last if stop the script..
// Instance message
$message = Swift_Message::newInstance();
$message->setSubject("subject")
->setFrom(array('noreply#email.test' => 'test'))
->setTo(array('a_valid_email' => 'name'))
->setBody("test", 'text/html')
->setPriority(2);
$smtp_host = 'smtp.mandrillapp.com';
$smtp_port = 587;
$smtp_username = 'valid_username';
$smtp_password = 'valid_password';
// SMTP
$smtp_param = Swift_SmtpTransport::newInstance($smtp_host , $smtp_port)
->setUsername($smtp_username)
->setPassword($smtp_password);
// Instance Swiftmailer
$instance_swiftmailer = Swift_Mailer::newInstance($smtp_param);
$type = $message->getHeaders()->get('Content-Type');
$type->setValue('text/html');
$type->setParameter('charset', 'iso-8859-1');
//Here the send function stop event and I did not go inside the if
if ($instance_swiftmailer->send($message, $fail)) {
echo 'OK ';
}else{
echo 'NOT OK : ';
print_r($fail);
}
Thank you in advance to help me to solve this problem..
If your code used to work, and now doesn't work, and you didn't change your code, then it's probably not a problem with your code. Check your Mandrill account validity - sometimes they suspend accounts for suspicious-appearing usage.
Im using the below php code to send an email to one address and bcc 2 other addresses. It sends to the recipient fine but I can only get it to send to one of the 2 bcc addresses. (see comments in code for what ive tried)
Oddly enough though, $result comes back as 3 so it seems that its trying to send the second bcc email but it never comes through.
<?php
$tracker='tracking#pnrbuilder.com';
$subject = $_POST['subject'];
$sender = $_POST['sender'];
$toEmail=$_POST['toEmail'];
$passedInEmail=stripslashes($_POST['message']);
$passedInEmail=preg_replace('/ /',' ',$passedInEmail);
require_once('swiftLib/simple_html_dom.php');
require_once('swiftLib/swift_required.php');
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
// Create the message
$message = Swift_Message::newInstance();
//turn the meesage into an object using simple_html_dom
//so we can iterate through and embed each image
$content = str_get_html($passedInEmail);
// Retrieve all img src tags and replace them with embedded images
foreach($content->find('img') as $e)
{
if($e->src != "")
{
$value = $e->src;
$newValue = $message->embed(Swift_Image::fromPath($value));
$e->src = $newValue;
}
}
$message->setSubject($subject);
$message->setFrom($sender);
$message->setTo($toEmail);
//this is my problem
$message->setBcc(array('tracking#pnrbuilder.com',$sender));
//as it is above only "sender" gets the email
//if I change it like this:
//$message->setBcc($tracker,$sender);
//only "tracker" gets the email
//same if I change it like this:
//$message->setBcc($sender);
//$message->addBcc($tracker);
$message->setReplyTo(array('flights#pnrbuilder.com'));
$message->setBody($content,'text/html');
$result = $mailer->send($message);
if ($result=3) {
echo 'Email Sent!';
}
else {
echo 'Error!';
}
?>
What is the proper way to do this?
You can find the swiftmailer tutorial here
example:
$message->setBcc(array(array('some#address.tld' => 'The Name'),array('another#address.tld' => 'Another Name')));
Try setting the names for the email addresses and see if it makes any difference.
This ended up being an issue on the server side, I contacted my hosting provider (GoDaddy) who were able to make some changes on their end fixing the problem. Thank you to all those who tried to help!