I'm using mandrill to manage my website emails.But I also want to use a mailbox like yahoo or google so I set a route in mandrill which forward inbound emails that will send to info#mydomain.com, to my default mail box(myEmail#ymail.com).I wrote a PHP code which receive an email, decode it, and forward it to a my email. I use SwiftMailer to send SMTP email.
It works nice for emails without any attachment.But there is a strange problem with attachments.They deliver corruptly.I can not open them.
I search throughly and test a lot, but unfortunately couldn't find the problem.
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
// ----------------- Send ----------------------------------------
include_once "swiftmailer-master/lib/swift_required.php";
$subject = $mail->msg->subject . " From " . $mail->msg->from_email;
$from = array('info#myDomain.ir' =>'myDomain');
$to = array(
'myEmail#yahoo.com' => 'Hamed Gh'
);
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 25,tls);
$transport->setUsername('username');
$transport->setPassword('***********');
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
//I think there is a problem here!!
foreach ($mail->msg->attachments as $attachment) {
$myType = $attachment->type;
$myName = $attachment->name;
$myContent = $attachment->content;
$attachment = Swift_Attachment::newInstance()
->setFilename($myName)
->setContentType($myType)
->setBody($myContent)
;
$message->attach($attachment);
}
$body = $mail->msg->html;
$message->setBody($body, 'text/html');
$message->setTo($to);
$text = "Mandrill speaks plaintext";
$message->addPart($text, 'text/plain');
if($recipients = $swift->send($message, $failures) )
{
echo 'Message successfully sent!';
} else {
echo "There was an error:\n";
print_r($failures);
}
?>
At the end I couldn't find the problem with SwiftMailer but I could answer my need with mandrill API,
this code works for me:
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
require 'mandrill/src/Mandrill.php';
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
$attachments = array();
foreach ($mail->msg->attachments as $attachment) {
$attachments[] = array(
'type' => $attachment->type,
'name' => $attachment->name,
'content' => $attachment->content,
);
}
$headers = array();
// Support only Reply-to header
if(isset($mail->msg->headers->{'Reply-to'})) {
$headers[] = array('Reply-to' => $mail->msg->headers->{'Reply-to'});
}
// ----------------- Send ----------------------------------------
try {
$mandrill = new Mandrill('-------------');
$message = array(
'html' => $mail->msg->html,
'text' => 'Example text content',
'subject' => $mail->msg->subject . " From " . $mail->msg->from_email,
'from_email' => 'info#mydomain.com',
'from_name' => 'info',
'to' => array(
array(
'email' => 'me#yahoo.com',
'name' => 'me',
'type' => 'to'
)
),
'headers' => array('Reply-To' => 'info#mydomain.com'),
'important' => false,
'track_opens' => null,
'track_clicks' => null,
'auto_text' => null,
'auto_html' => null,
'inline_css' => null,
'url_strip_qs' => null,
'preserve_recipients' => null,
'view_content_link' => null,
'bcc_address' => null,
'tracking_domain' => null,
'signing_domain' => null,
'return_path_domain' => null,
'merge' => true,
'attachments' => $attachments
);
$async = false;
$ip_pool = 'Main Pool';
$send_at = null;
$result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
} catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
?>
Related
First Time i used Mandrill API to send email,
But I got this error.
A mandrill error occurred: Mandrill_ValidationError - You must specify a key value
Fatal error: Uncaught exception 'Mandrill_ValidationError' with message 'You must specify a key value' in mandrill-api-php/src/Mandrill.php:153 Stack trace: #0 mandrill-api-php/src/Mandrill.php(132): Mandrill->castError(Array) #1 mandrill-api-php/src/Mandrill/Messages.php(80): Mandrill->call('messages/send', Array) #2 mandrill.php(88): Mandrill_Messages->send(Array, false) #3 {main} thrown in Mandrill.php on line 153
This is my code
<?php
require_once 'mandrill-api-php/src/Mandrill.php';
$servername = "localhost";
$username = "root";
$password = "";
$table = '';
$conn = mysql_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$selected = mysql_select_db("DB Name")
or die("Could not select database");
$query=mysql_query(Query);
$table .= "<table width='auto' height='auto' border='1' bordercolor='#003399' style='color:#FF0000;table-layout:fixed' cellpadding=0 cellspacing=0>
<tr>
<th>User ID</th>
<th>Full Name</th>
<th>Username</th>
<th>Email ID</th>
</tr>";
while($row = mysql_fetch_array($query))
{
$table .= "<tr>";
$table .= "<td>" . $row['id'] . "</td>";
$table .= "<td>" . $row['fullname'] . "</td>";
$table .= "<td>" . $row['username'] . "</td>";
$table .= "<td>" . $row['useremail'] . "</td>";
$table .= "</tr>";
}
$table .= "</table><br>";
try {
$mandrill = new Mandrill(API Key);
$message = array(
'html' => $table,
'subject' => 'Notification Email',
'from_email' => 'Example#example.com',
'from_name' => 'Test',
'to' => array(
array(
'email' => 'Example#example.com',
'name' => 'Test',
'type' => 'to'
)
),
'important' => false,
'track_opens' => null,
'track_clicks' => null,
'auto_text' => null,
'auto_html' => null,
'inline_css' => null,
'url_strip_qs' => null,
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
?>
'preserve_recipients' => null,
'view_content_link' => null,
'tracking_domain' => null,
'signing_domain' => null,
'return_path_domain' => null,
);
$async = false;
$result = $mandrill->messages->send($message, $async);
print_r($result);
}
catch(Mandrill_Error $e) {
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
throw $e;
}
?>
<pre>/*
Before coding, you have to make configurations in Mandrill.
Step 1: Enter Mandrill and register your domain.
Step 2: Configure DNS: DKIM and SPF (This is a good tutorial: https://www.youtube.com/watch?v=uEjP_smeLjU) at https://mandrillapp.com/settings/sending-domains
Step 3: Get a KEY API (https://mandrillapp.com/settings)
Step 4: Code with PHP
Step 5: Good luck! :)
*/
/*LIBS*/
include 'lib/mandrill-api-php/src/Mandrill.php';
$mandrill = new Mandrill('YOUR API KEY HERE');
/*ADMIN AND USER EMAIL*/
$admin_email = 'your_email#your_domain.com';
$client_email = 'the_email_of_the_client#mail.com';
/*attach PDF*/
$attachment = file_get_contents('the_route_to_your_pdf');
$attachment_encoded = base64_encode($attachment);
try{
$user_message = array(
'subject' => 'Your Subject here',
'from_email' => $admin_email,
'from_name' => 'your_domain_for_example',
'html' => '<p>AquĆ va la plantilla HMTL</p>',
'to' => array(array('email' => $client_email, 'name' => 'Recipient 1')),
'merge_vars' => array(array(
'rcpt' => 'recipient1#domain.com',
'vars' =>
array(
array(
'name' => 'FIRSTNAME',
'content' => 'Recipient 1 first name'),
array(
'name' => 'LASTNAME',
'content' => 'Last name')
))),
'attachments' => array(
array(
'content' => $attachment_encoded,
'type' => "application/pdf",
'name' => 'the_name_of_the_attach.pdf',
))
);
$res_user_mandrill = $mandrill->messages->send($user_message, $async=false, $ip_pool=null, $send_at=null);
} catch(Mandrill_Error $e) {
}
</pre>
I am using mailchimp api v2. I am using the mailchimp recommended full api v2 php wrapper. I am able to create a campaign, but not sure how to send it. With the send method, It wants the campaign id, but I am letting mailchimp create the campaign id when creating the campaign.
My create campaign code looks like this:
$api_key = "my_api_key";
require('Mailchimp.php');
//Create Campaign
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subject',
'from_email' => 'test#test.com',
'from_name' => 'From Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'didnt work';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
}
This seems to be working for me.
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subjects',
'from_email' => 'test#test.com',
'from_name' => 'From_Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'sorry';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
$mySend = $Mailchimp->campaigns->send($result['id']);
}
I am trying to send email using AWS SES using the following PHP script:
<?php
require_once("phar://aws.phar");
use Aws\Ses\SesClient;
//Open client
$client = SesClient::factory(array(
"key" => "key",
"secret" => "secret",
"region" => "region"
));
$subject = "subject";
$messageText = "text message";
$messageHtml = "<h1>formatted message</h1>";
//Send email
try{
$response = $client->sendEmail(
array(
'Source' => 'verified_email#domain.com',
'Destination' => array(
'ToAddresses' => array('an_address#domain.com')
),
'Message' => array(
'Subject' => array('Data' => $subject),
'Body' => array('Text' => array('Data' => $messageText)),
'Html' => array('Data' => $messageHtml)
)
)
);
}catch(Exception $e){
//An error happened and the email did not get sent
echo($e->getMessage());
}
?>
Whenever I run this, it goes to the catch clause and prints to the screen the message:
Unable to determine service/operation name to be authorized
This doesn't really give me any information on what's wrong and there's no documentation on the API page about this. Any ideas?
I've been trying to send emails with Pear on xampp through Gmail, and after spending hours setting it all up and figuring out all the errors I was getting, I thought I was so close, until I started getting this error:
controller action
public function automail() {
App::uses('CakeEmail', 'Network/Email');
$ret_msg = null;
try {
$is_call_email = true;
$subject = "case detail";
$comment = "Ready to Review";
$email_to = "exmaple#gmail.com";
if ($is_call_email == true) {
$email_to = str_replace(' ', '', $email_to);
$email_addresses = preg_split('/[;,]/', $email_to);
$this->log($is_call_email,'bool');
$email = new CakeEmail();
$email->from(array($this->Session->read('Auth.User.email') => $this->Session->read('Auth.User.name')))
->to($email_addresses)
->subject($subject)
->send($comment);
$this->log($subject,'subject');
}
} catch (Exception $ex) {
$ret_msg = $ex->getMessage();
$this->log($ex->getLine(), 'emailError');
}
$this->log('Return msg is = ' . $ret_msg, 'shared');
return;
in email.php
<?php
class EmailConfig {
public $default = array(
'host' => 'ssl://smtp.gmail.com',
'port' => 465,
'username' => 'example#gmail.com', //example#gmail.com
'password' => 'secret',
'transport' => 'Smtp',
'from' => array('exampe#gmail.com' => 'Nam Email'),
'log' => true
);
}
from and to both are same email addresses because i was send in my account for testing...
please help me or any advice for how to send email using cakephp....
You need to specify $email->config. Like:
$email->config('default')
->from(array($this->Session->read('Auth.User.email') => $this->Session->read('Auth.User.name')))
->to($email_addresses)
->subject($subject)
->send($comment);
could you help me
I write this code to send node after saving it
this node has an attached file may be pdf doc and docx
I have used this hook
this could send an empty mail with html attached file contain the mail body not the file contents
function footer_node_insert($node){
if($node->type=="application_form"){
$file_data=file_load($node->field_cv['und'][0]['fid']);
$filemime=$file_data->filemime;
$filename=$file_data->filename;
$file_uri=file_create_url($file_data->uri);
$job=node_load($node->field_apply['und'][0]['nid']);
$to='mail#mail.com';
$key = "notice";
$module = 'footer';
$message = drupal_mail($module, $key, $to, language_default(), array(), "from#froom.com", True);
// Build the default headers
$headers = array(
'MIME-Version' => '1.0',
'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
'Content-Transfer-Encoding' => '8Bit',
'X-Mailer' => 'Drupal',
);
$attachment = array(
'filecontent' => file_get_contents($file_uri),
'filename' =>$filename,
'filemime' =>$filemime
);
$message['headers']['Content-Type'] = $headers ;
$message['subject'] = 'Apply for ' .$job->title . ' Page';
$body = array();
$body[] = '<b>'. t('Name:').'</b>'.$node->title;
$body[] = '<b>'. t('Email:').'</b>'.$node->field_application_email['und']['0']['email'] ;
$body[] = '<b>'. t('Current Job:').'</b>'.$node->field_current_job['und']['0']['value'];
$body[] = '<b>'. t('Current Company:').'</b>'.$node->field_current_company['und']['0']['value'];
$body[] = '<b>'. t('Home Phone:').'</b>'.$node->field_home_phone['und']['0']['value'];
$body[] = '<b>'. t('Mobile Phone:').'</b>'.$node->field_mobile_phone['und']['0']['value'];
$message['body'] = implode('<br>', $body);
$message['params']['attachments'][] = $attachment;
// Retrieve the responsible implementation for this message.
$system = drupal_mail_system($module, $key);
// Format the message body.
// $message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);
if ($message['result']) {
echo 'true';
} else {
echo 'false';
}
exit();
}
}
i have do something like this to send html mail.
First you need to override the format to send message.
In your file module.inc
write this code.
<?php
change this template use File | Settings | File Templates.
*/
/**
* Modify the drupal mail system to send HTML emails.
*/
class ReservationInvitationMailSystem extends DefaultMailSystem {
/**
* Concatenate and wrap the e-mail body for plain-text mails.
*
* #param $message
* A message array, as described in hook_mail_alter().
*
* #return
* The formatted $message.
*/
public function format(array $message) {
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
/* $message['body'] = implode("\n\n", $message['params']['body']);*/
$message['body'] = drupal_wrap_mail($message['params']['body']);
return $message;
}
}
In your module.module before to call drupal_mail
set your format mail
variable_set('mail_system', array('reservation_invitation_reservation_invitation_key' => 'ReservationInvitationMailSystem'));
Upadate your function like this and add your attach file
function reservation_invitation_mail_send($form_values, $node) {
$module = 'reservation_invitation';
$key = 'reservation_invitation_key';
//$to = $form_values['email'];
$to= "Yourmail#icilalune.com";
$cc= $node->content['field_invited_by_ref']['#object']->field_invited_by_ref['und']['0']['entity']->field_email_address['und']['0']['value'];
$bbc= $node->content['field_invited_by_ref']['#object']->field_main_guest['und']['0']['entity']->field_email_address['und']['0']['value'];
$from = variable_get('site_mail', 'bacar#icilalune.com');
$params = $form_values;
$params['headers'] = array(
'Bcc' => $bbc,
'Cc' => $cc);
$params['subject']= t('Your invitation!');
$params['body']= theme('reservation_invitation_moet_template',array('var_name'=>$params));
$language = language_default();
$send = TRUE;
variable_set('mail_system', array('reservation_invitation_reservation_invitation_key' => 'ReservationInvitationMailSystem'));
$message = drupal_mail($module, $key, $to, $language, $params, $from, $send);
/* $system = drupal_mail_system($module, $key);
// Format the message body.
$message = $system->format($message);
// Send e-mail.
$message['result'] = $system->mail($message);*/
if($message['result'] == TRUE) {
drupal_set_message(t('Your message has been sent.'));
}
else{
drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
}
}
My working Drupal 7 solution with module MimeMail without invoking hook_mail():
// Load attachment.
$file = file_load($fid);
$to = 'something#email.com';
$from = 'something#email.com';
$subject = 'Invoice ' . $file->filename;
$module = 'mimemail';
$token = time();
$message = array(
'id' => $module . '_' . $token,
'to' => $to,
'subject' => $subject,
'body' => array('something text...'),
'headers' => array(
'From' => $from,
'Sender' => $from,
'Return-Path' => $from,
'MIME-Version' => '1.0',
'Content-Type' => 'text/html; charset=UTF-8',
),
'params' => array(
'attachments' => array(
0 => array(
'path' => file_stream_wrapper_get_instance_by_uri($file->uri)->realpath(),
'filecontent' => file_get_contents($file->uri),
'filename' => $file->filename,
'mime' => $file->filemime,
'encoding' => 'base64',
'disposition' => 'attachment',
'list' => TRUE,
),
),
),
);
$system = drupal_mail_system($module, $token);
$message = $system->format($message);
if ($system->mail($message)) {
return TRUE;
}
else {
return FALSE;
}