Trouble using PEAR's Mail_Queue - php

I'm trying to implement PEAR's Mail_Queue package to queue some emails for a web application. I've used the documentation at http://pear.php.net/manual/en/package.mail.mail-queue.mail-queue.tutorial.php to write a small test script.
My problem is that the database is not being updated, and it's not producing errors.
EDIT
// mail_queue db options
$db_options['type'] = 'mdb2';
$db_options['dsn'] = DSN;
$db_options['mail_table'] = 'mail_queue';
// mail_queue sending options
$mail_options['driver'] = 'smtp';
$mail_options['host'] = 'smtp.gmail.com';
$mail_options['port'] = 25;
$mail_options['localhost'] = $host;
$mail_options['auth'] = true;
$mail_options['user'] = MAILUSER;
$mail_options['pass'] = MAILPASS;
require "Queue.php";
$mail_queue =& new Mail_Queue($db_options,$mail_options);
$from = 'someone#domain.ca';
$to = 'martin#starmedia.ca';
$message = 'This is a test';
$headers = array('From' => $from,
'To' => $to,
'Subject' => 'Someone has sent you an email!');
$mime =& new Mail_mime();
$mime->setTXTBody($message);
$body = $mime->get();
$headers = $mime->headers($headers,true);
print $mail_queue->put($from,$to,$headers,$body);
This produces the error Mail Queue Error: Cannot connect to database . However I checked all of the connection information and it's correct. Also, adding if (PEAR::isError($mail)) die($mail->getMessage()); produces no errors!

OK, I finally have my mail queue file working. Here are the steps I took to get it to function:
1. Enable error messages
To enable error handling, I added this snippet:
function handle_pear_error($e) {
die($e->getMessage() . ' ' . print_r($e->getUserInfo(), true));
}
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'handle_pear_error');
Once I added this, I reloaded the page and I was getting the following error:
Call to undefined function: MDB2_Driver_mysql::_isNewLinkSet()
2. Update MDB2's MySQL driver
I searched that error and found that it's usually a result of either not having an up-to-date MDB2 library or its MySQL driver.
So I updated both and it's working!

Related

How to fix [HTTP 403] Unable to create record in twilio?

I'm trying to implement fax sending and receiving using laravel. But unfortunately, I'm getting this error. Please see the error and my code below.
Error
Twilio\Exceptions\RestException
[HTTP 403] Unable to create record: '+15005550006' is not a valid destination for trial accounts
Code
public function send()
{
$sid = env('TWILIO_ACCOUNT_SID');
$token = env('TWILIO_AUTH_TOKEN');
$to = env('TO_EXAMPLE');
$twilio = new Client($sid, $token);
$mediaURL = asset('pdfs/dummy.pdf');
$from = ["from" => '+' . env('TWILIO_NUMBER')];
$fax = $twilio->fax->v1->faxes
->create('+' . $to, $mediaURL, $from);
print($fax->sid);
}
Reference
https://www.twilio.com/docs/fax/quickstart
Do not use your TEST credentials. Use your LIVE credentials. +15005550006 is reserved for use with TEST credentials.
How To Use Twilio Test Credentials with Magic Phone Numbers

How to fix "401Array{"errors":[{"message":"Permission denied, wrong credentials","field":null,"help":null}]}" error in PHP/Sendgrid/Heroku?

BROWSER ERROR is: 401Array{"errors":[{"message":"Permission denied, wrong credentials","field":null,"help":null}]}
I have written this code to send an email using sendgrid addon of heroku. Instead of api_key I wrote my own. What is the problem? Why such error?
require("sendgrid-php/sendgrid-php.php");
$from = new SendGrid\Email(null, "kesursweta#yahoo.com");
$subject = "Hello World from the SendGrid PHP Library!";
$to = new SendGrid\Email(null, "kesursweta#yahoo.com");
$content = new SendGrid\Content("text/plain", "Hello, Email!");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$apiKey = getenv('my_api_key');
$sg = new \SendGrid($apiKey);
$response = $sg->client->mail()->send()->post($mail);
echo $response->statusCode();
echo $response->headers();
echo $response->body();
First try out running this code with composer and then create and set SENDGRID_API_KEY. After performing both this task your code will not show any error.For reference please checkout this links:
Download composer from here: https://gist.github.com/tomysmile/3b37ab4a1ddd604093fe724d0a882166
How to create and set API_KEY: https://github.com/sendgrid/sendgrid-php

Gmail API with PHP mailer can't send multiple attachments

I am using PHPmailer with Gmail API to send out mail. This process has worked very well for me for sending just standard emails, however, I want to also have the ability to send out an email with attachments using the Gmail API. When I tried using $mail->addAttachment($urlString, $name); Gmail would come back with the error Request Entity Too Large Error 413 (The size of the attachments never goes above 20MB so it should be well within the 35MB limits of Gmail API).
After some searching, I found out it was because I wasn't using "/Upload URI" for sending large Gmail Attachments (Anything above 5mb and below 35mb). Problem is, I am not very knowledgeable on how to work the Gmail API and only got what I have now from basically copying code from somewhere else and slightly modifying it for my uses and as such, I have no idea how to change the URI like that.
Here is what I have so far, that works with standard emails:
function($agent, $assistantName='', $assistantEmail='', $subject, $body, $attachments=''){
$key = realpath(dirname(__FILE__).'/Services/Google/Gmail.json');
$useremail = 'myuseremail#example.com';
$toAddress = $agent->email;
$agentFirst = $agent->first_name;
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS='.$key);
$client->useApplicationDefaultCredentials();
$user_to_impersonate = $useremail;
$client->setSubject($user_to_impersonate);
$client->addScope('https://www.googleapis.com/auth/gmail.compose');
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
//prepare the mail with PHPMailer
$mail = new PHPMailer();
$mail->CharSet = "UTF-8";
$mail->Encoding = "base64";
$subject = $subject;
$msg = $body;
$from = $useremail;
$fname = "My Name";
$mail->From = $from;
$mail->FromName = $fname;
$mail->AddAddress($toAddress, $agentFirst);
$mail->AddCC($assistantEmail, $assistantName);
$mail->AddReplyTo($from,$fname);
if ($attachments != '') {
foreach ($attachments as $name => $urlString) {
$mail->addAttachment($urlString, $name);
}
}
$mail->Subject = $subject;
$mail->Body = $msg;
$mail->IsHTML(true);
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$m = new Google_Service_Gmail_Message();
$data = base64_encode($mime);
$data = str_replace(array('+','/','='),array('-','_',''),$data); // url safe
$m->setRaw($data);
$service = new Google_Service_Gmail($client);
$email = $service->users_messages->send($useremail, $m);
return json_encode($email);
}
I don't really know where to go from here, so any help would be appreciated.
use EZCMail and build the email structure yourself... it is very pickey! I can post some details after.
you may also have to send the email in chunks.
If the email is over 4MB then you are going to have to send in chunks using Google_Http_MediaFileUpload
Your code using this should be something similar to this, there is examples for using Google_Http_MediaFileUpload elsewhere on the web which might be more complete:
$client->setDefer(true);
// Call the API with the media upload, defer so it doesn't immediately return.
$arrRequestParams = $arrRequestParams+['uploadType' => 'multipart'];
$result = $this->TransportPrepSwitch($strAction, $objGMessage, $arrRequestParams); // Make draft or message $service->users_messages->send('me', $objGMessage, $arrRequestParams);
$mailMessage = base64url_decode($strRaw);
// create mediafile upload
$chunkSizeBytes = 1*1024*1024; // send to google in 1MB chunks
$media = new Google_Http_MediaFileUpload($client,$result,'message/rfc822',$mailMessage,true,$chunkSizeBytes);
$media->setFileSize(strlen($mailMessage));
// Upload chunks. Status will contain the completed $result.
$status = false;
set_time_limit(300);
while(!$status)
$status = $media->nextChunk();
// Reset to the client to execute requests immediately in the future.
$client->setDefer(false);
$objResponce = $status;
Also the structure of the email parts MUST be as follows:
multipart/mixed => [
multipart/related => [
multipart/alternative => [
plain,
html
],
inline images,
],
attachments,
]
The only way I could achieve this was using EZCMail to build the email part by part.

Swiftmailer breaks down after staging

I'm bringing the (Laravel-based) website for an event that's coming up soon, up to date. Part of this was improving the mailing function, for which I decided to use Mandrill's SMTP with SwiftMailer. Everything worked perfectly while working locally. However, since we pushed everything to a live (well, testing, but on the same server as live) staging area, no mails get sent anymore.
Everything seems to break down after I make a send() command in PHP. Even a simple print command doesn't do anything. There's also no errors being reported, except if I go look in my console, where the request returns a 500 Internal Server Error, without any other errors.
At the moment, these are the function I'm using only to test, which works and sends perfectly on local and then prints, but just gives a white screen on the staging area...
Route::any('test', function()
{
testMail();
//this print works perfectly locally but shows nothing on staging
print ('boe');
});
function testMail(){
$to = array('private#email.address' => 'My Name');
$subject = 'test mail';
$text = "test mail hier";
$htmlTekst = "<b>boe</b><i>spaghetti</i>";
$view = View::make('mailTemplate',
['naam' => 'Jeroen Cuvelier',
'tekst' => $htmlTekst,
'username' => 'my email address',
'password' => 99999,
'siteUrl' => rootUrl(),
'header2' => '']);
$html = $view->render();
sendEmail($text, $html, $to, $subject, "", "");}
function sendEmail($text, $html, $to, $subject, $attachment, $attachmentName)
{
//$subject = 'Subject!';
$from = array('event#email.company' =>'Company event');
/*
SMTP-settings
*/
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 25);
$transport->setUsername('MY_MANDRILL_USERNAME');
$transport->setPassword('MY_MANDRILL_PASSWORD');
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
$message->setBody($html, 'text/html');
$message->setTo($to);
$message->addPart($text, 'text/plain');
if ($attachment != "")
{
$toAttach = Swift_Attachment::fromPath($attachment);
if ($attachmentName!="")
{
$toAttach->setFilename($attachmentName);
}
$message->attach($toAttach);
}
//neither of these messages print on staging
if ($recipients = $swift->send($message, $failures))
{
echo 'Message successfully sent!';
} else {
echo "There was an error:\n";
print_r($failures);
}
}
Turns out the problem was not in PHP or anything I had done. The server just didn't allow SMTP calls. A call to the company hosting that fixed my issues.

Error when Sending Mail with Attachments Using PEAR

My page continues to error out (Error 324 - Chrome) when attempting to send e-mails with attachments using PHP's PEAR Mail extension. Although the page error's out - I do receive one of the approximately 800 e-mails. Here's what I'm working with:
function email_statements($type) {
switch($type) {
// Determine the type of statement to be e-mailed
case 'monthly':
// Array holding all unique AP e-mail addresses
$ap_email_addresses = array();
include('../path/to/db/connection/params.php');
// Grab the unique AP e-mail address set to receive statements
$stmt = $mysqli->prepare("SELECT email FROM statements GROUP BY email ORDER BY email ASC");
$stmt->execute();
$stmt->bind_result($ap_email_address);
// Add unique e-mail address to AP E-mail Addresses array
while($row = $stmt->fetch()) $ap_email_addresses[] = $ap_email_address;
$stmt->close();
$mysqli->close();
// Verify we grabbed the e-mail addresses
if(count($ap_email_addresses) == 0) {
// Exit and return error code if unable to grab e-mail addresses
$return_message = 1;
exit;
}
// E-mail addresses grabbed - proceed
else {
// PDF formatted date
date_default_timezone_set('America/New_York');
$formatted_date = date('m_d_Y');
// Now we have the unique e-mail addresses - associate those with the account numbers
include('../path/to/db/connection/params.php');
foreach($ap_email_addresses as $email_address) {
$file_names = array();
$stmt = $mysqli->prepare("SELECT customer_number FROM statements WHERE email = ?");
$stmt->bind_param("s", $email_address);
$stmt->execute();
$stmt->bind_result($ap_account_number);
// Constructs the name of the statement (PDF) file to be sent
while($output = $stmt->fetch()) $file_names[] = $ap_account_number . '_' . $formatted_date . '.pdf';
// Send e-mails
include('Mail.php');
include('Mail/mime.php');
// Include SMTP authentication parameters
include('../path/to/email/info.php');
// Set the e-mail recipients
$recipients = 'example#example.com';
// Set the e-mail subject
$subject = 'Monthly Account Statement';
// Create the e-mail body
$html =
'<html>
<body>
<p>Test E-mail</p>
</body>
</html>';
// Construct the message headers
$headers = array(
'From' => $from,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8',
'MIME-Version' => '1.0'
);
$mimeparams = array();
$mimeparams['text_encoding'] = '8bit';
$mimeparams['text_charset'] = 'UTF-8';
$mimeparams['html_charset'] = 'UTF-8';
$mimeparams['head_charset'] = 'UTF-8';
// Create a new instance
$mime = new Mail_mime();
// Specify the e-mail body
$mime->setHTMLBody($html);
// Attach the statements (PDF)
foreach($file_names as $attached_file) {
$file = '../path/to/the/pdf/file/' . $attached_file;
$file_name = $attached_file;
$content_type = "Application/pdf";
$mime->addAttachment ($file, $content_type, $file_name, 1);
}
// Create the body
$body = $mime->get($mimeparams);
// Add the headers
$headers = $mime->headers($headers);
// Create SMTP connect array to be passed
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
// Send the message
$mail = $smtp->send($recipients, $headers, $body);
if(PEAR::isError($mail)) echo 'Error';
else echo 'Sent';
// Close this account and cycle through the rest
$stmt->close();
}
$mysqli->close();
}
break;
}
}
Now I thought maybe I wasn't giving the script enough time to execute - so I set it ridiculously high set_time_limit(99999999) to ensure it had plenty of time, although it normally times out within 10-15 seconds. So basically it works like this, I have an internal DB that stores customer account numbers and e-mail addresses. Accounts can have the same e-mail address (It's sent to their company's AP department) - aka one e-mail address receives statements for multiple branches. From their each statement is already constructed with the format being ACCOUNTNUMBER_MM_DD_YYYY.pdf.
So I'm simply trying to have a short message in the body, and attach the monthly statements. Again, not sure why it's failing, and even though the script halts, I do receive ONE of the e-mails (I'm sending them all to myself at the moment just to test). Can anyone see where I may have an issue?
I discovered the issue. As of PHP 5.0+ you cannot have multiple instances of the same include file - aka Mail.php was included as it looped. Once it was moved outside of the loop, the issue was resolved.

Categories