Mandrill PHP library - FROM field - php

How can I set a proper FROM field for the PHP Mandrill library?
In Java, I can use:
from = "Some Description <noreply#domain.com>";
If I try the same in PHP, I get an error:
Validation error: {"message":{"from_email":"The username portion of the email address is invalid (the portion before the #: Some Description
Only emails with FROMs like this get through:
$from = "noreply#domain.com";
In case it matters, here's how I send an email:
$from = "Some Description <noreply#domain.com>";
$message = array("subject" => $aSubject, "from_email" => $from, "html" => $aBody, "to" => $to);
$response = $mandrill->messages->send($message, $async = false, $ip_pool = null, $send_at = null);

If you read the documentation https://mandrillapp.com/api/docs/messages.html it has two parameters in request
from_email and from_name when we pass
$from = "Name <email>",
It is not accepted by mandrill hence it throws error , To pass a name you need to pass from_name with name value.

Related

Updating an email's subject using Microsoft Graph in PHP

Here's my current code:
require_once '/pathtovendor/vendor/autoload.php';
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
use Microsoft\Graph\Http\GraphRequest;
$access_token = "My valid access token";
$graph = new Graph();
$graph->setAccessToken($access_token);
$reply = array( "Comment" => "My reply" );
$message_id = "Valid message ID";
if($graph->createRequest("POST", "/me/messages/".$message_id."/reply")
->attachBody($reply)
->execute()){
// I can get to this part OK. Message is replied to.
//This code doesn't work
$graph->createRequest("PATCH", "/me/messages/".$message_id)
->attachBody(array( "Subject" => "New Subject" ))
->execute();
}
I can run GET and POST requests which work, but I can't get PATCH to work this way. It continues to throw a 500 Internal Server Error. Any help is appreciated.
This is only supported on draft messages. From the documentation:
subject | String |
The subject of the message. Updatable only if isDraft = true.
The following properties can only be updated in draft messages:
bccRecipients
body
ccRecipients
internetMessageId
replyTo
sender
subject
toRecipients
from

Php code to send message to multiple recipient with different message body

I'm trying to send messages to multiple recipients with different message body but I don't know if my script has any error. The problem is when I execute this below code, only one user email will receive message. If I try it again another one will get a message. I want all the emails in the array to receive the message with individual message body. And also I noticed that my script takes long to complete execution. Is there a better way to get this working as expected?
PHP
<?php
$conn_handler->prepare('
SELECT * FROM food_orders fo
INNER JOIN our_chefs oc
ON oc.chef_private_key = fo.order_chefpkey
WHERE fo.order_id = :currentorder AND fo.order_userid = :order_userid
ORDER BY fo.order_chefpkey
');
$conn_handler->bind(':currentorder', $lastOrderId);
$conn_handler->bind(':order_userid', $buyerid);
$conn_handler->execute();
$getFoodOrders = $conn_handler->getAll();
if( !isset($_SESSION['completed_'.$lastOrderId]) ) {
$creatProducts = array();
$email_list = array();
/*Here i loop on current orders*/
foreach($getFoodOrders as $row) {
//Create an array of chef emails
$email_list[$row->chef_private_key] = $row->chef_email;
//Create an array of items based on chef private key
$creatProducts[$row->order_chefpkey][] = array(
'o_name' => $row->order_foodname,
'o_pid' => $row->oder_foodid,
'o_price' => $row->order_price,
'o_currency' => $row->currency,
'o_qty' => $row->order_qty,
'o_size' => $row->order_size,
'o_img' => $row->order_image,
);
}
//Here i loop through the above chef emails
foreach($email_list as $key => $val) {
$productBuilder = null;
//Here i create html for products based on chef keys
foreach($creatProducts[$key] as $erow) {
$productBuilder .= '<div><b>Product Name:</b> '.$erow['o_name'].'<br/></div>';
}
//Here i send email to each chef with their individual products created above
$sourcejail->sendMail(
$val, //Send TO
null, //Send Bcc
null, //Send CC
null, //reply To
1, //Something
'Your have received new order ('.$lastOrderId.')', //Subject
$productBuilder //Message body
);
}
$_SESSION['completed_'.$lastOrderId] = true;
}

How to pass dynamic data to email template of sendgrid?

I have integrated sendgrid in Laravel and I managed to send the email template of sendgrid in emails but I am not able to replace the content in the email templates. I am using Sendgrid Web API V3.
I followed the steps given in the below link but it is not replacing the variables in template with my dynamic data.
Link: How to pass dynamic data to email template desgined on sendgrid webapp ? :-| Sendgrid
Here is code
$sg = new \SendGrid('API_KEY');
$request_body = json_decode('{
"personalizations":[
{
"to":[
{
"email":"example#example.com"
}
],
"subject":"Hello World from the SendGrid PHP Library!"
}
],
"from":{
"email":"from#example.com"
},
"content":[
{
"type":"text/html",
"value":"<html><body> -name- </body></html>"
}
],
"sub": {
"-name-": ["Alice"]
},
"template_id":"xxxxxx-xxx-xxxxxxxx"
}');
$mailresponse = $sg->client->mail()->send()->post($request_body);
echo $mailresponse->statusCode();
echo $mailresponse->body();
echo $mailresponse->headers();
Please help.
This works perfectly and is much simpler than the solutions already posted:
$email = new \SendGrid\Mail\Mail();
$email->setFrom( "from#example.com", "Some guy" );
$email->addTo( "to#example.com", "Another guy" );
$email->setTemplateId(
new \SendGrid\Mail\TemplateId( TEMPLATE_ID )
);
// === Here comes the dynamic template data! ===
$email->addDynamicTemplateDatas( [
'variable1' => 'Some stuff',
'templatesRock' => 'They sure do!'
] );
$sendgrid = new \SendGrid( API_KEY );
$response = $sendgrid->send( $email );
I have overcome this issue by using another way. Below is code that is working fine. May be help some one..
//create mail object
$mail = new \SendGrid\Mail();
//set from
$from = new \SendGrid\Email("SENDER NAME", "SENDER EMAIL");
$mail->setFrom($from);
//set personalization
$personalization = new \SendGrid\Personalization();
$to = new \SendGrid\Email("RECEIVER NAME", "RECEIVER EMAIL");
$personalization->addTo($to);
$personalization->setSubject("SUBJECT");
//add substitutions (Dynamic value to be change in template)
$personalization->addSubstitution(':name', "Any");
$mail->addPersonalization($personalization);
$mail->setTemplateId("TEMPLATE_ID");
//send email
$sg = new \SendGrid("API_KEY");
$response = $sg->client->mail()->send()->post($mail);
It's a little bit late but maybe this can help some one to. I faced the same problem and #bwest answer helped me to solve it:
The substitutions values cannot be an array and the should look like:
`"personalizations":[{
"to":[{
"email":"example#example.com"
}],
"subject":"Hello World from the SendGrid PHP Library!",
"substitutions": {
"-name-": "Alice"
}
}
],
...
IN JAVA use:
Personalization personalization = new Personalization();
and its methods for sending the dynamic data to sendgrid template and use {{}}
for receiving the data on sendgrid.

check if domain exists using PHP PEAR Mail class

I noticed that my server has been returning this error when trying to send email to an invalid domain:
Standard Message: Failed to set sender: user#invaliddomain.coom [SMTP: Invalid response code received from server (code: 553, response: 5.1.8 ... Domain of sender address user#invaliddomain.coom does not exist)]
Standard Code: 10004
DBMS/User Message:
DBMS/Debug Message:
Is there a way to check the domain first before attempting to send the email? I have a feeling I could also handle this on the SMTP server end by squelching this error, but I like the idea of being able to test an email domain first before sending it. Thanks for your ideas!
Here is the pertinent code just for reference (variables are filtered in from a form):
$headers['To'] = $to_address;
$headers['From'] = $from;
$headers['Reply-To'] = $from;
$headers['Subject'] = $subject;
$this->setHTMLBody($body);
$body = $this->get(array('text_charset' => 'utf-8'));
$headers = $this->headers($headers, true);
$message =& Mail::factory('smtp');
$mail = $message->send($to_address,$headers,$body);
You could use Net_DNS2 to determine if the domain exists and if so, send the email on it's merry way.
include "Net/DNS2.php";
$r = new Net_DNS2_Resolver();
try {
$result = $r->query($domain, 'MX');
} catch(Net_DNS2_Exception $e) {
$result = null;
}
if ($result !== null) {
// send email...
}
Naturally, I'd suggest some level of caching so you aren't repeating lookups.

problem sending email with attachment

I'm new to using EWS from Exchangeclient classes.
I'm looking for a simple example how to send an email with an attachment. I've found examples about how to send an email but not sending an email with an attachment.
This is my script:
$exchangeclient = new Exchangeclient();
$exchangeclient->init($username, $password, NULL, 'ews/Services.wsdl');
$exchangeclient->send_message($mail_from, $subject, $body, 'HTML', true, true);
I have the following soap request.
$CreateItem->MessageDisposition = "SendAndSaveCopy";
$CreateItem->SavedItemFolderId->DistinguishedFolderId->Id = "sentitems";
$CreateItem->Items->Message->ItemClass = "IPM.Note";
$CreateItem->Items->Message->Subject = $subject;
$CreateItem->Items->Message->Body->BodyType = $bodytype;
$CreateItem->Items->Message->Body->_ = $content;
$CreateItem->Items->Message->ToRecipients->Mailbox->EmailAddress = $to;
$CreateItem->Items->Message->Attachments->FileAttachment->AttachmentId = $attach['AttachmentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Name = $attach['Name'];
$CreateItem->Items->Message->Attachments->FileAttachment->ContentType = $attach['ContentType'];
$CreateItem->Items->Message->Attachments->FileAttachment->ContentId = $attach['AttachmentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Content = $attach['ContentId'];
$CreateItem->Items->Message->Attachments->FileAttachment->Size = $attach['Size'];
The error I am getting is:
Fatal error: Uncaught SoapFault exception: [a:ErrorSchemaValidation] The request failed schema validation: The required attribute 'Id' is missing.
In order to send email with an attachment you have to first create the Message (Item) without any recipients (and a MessageDisposition of "SendToNone" or something like that) and save it in your Drafts folder. THEN create a request for a CreateAttachment, like so, where $key is the changekey of the item you created earlier (you have to read back the server response and save the changekey somewhere, because the changekey changes for an item with every modification it undergoes):
$attachrequest->ParentItemId->ChangeKey = $key;
$attachrequest->Attachments->FileAttachment->Name = $attachment_name;
$attachrequest->Attachments->FileAttachment->ContentLocation = $attachment;
$attachrequest->Attachments->FileAttachment->Content = $attachment_content;
$attachrequest->Attachments->FileAttachment->ContentType = $attachment_contenttype;
$response = self::$ews->CreateAttachment($attachrequest);
THEN you update the message (with an UpdateItem) to include recipients and so that the MessageDisposition is something like SendToAllAndSaveCopy.
(Disclaimer: I'm using this method now and it's all working fine, except for identifying the right format for Attachments->FileAttachment->Content, which looks like it should be the encoded base64 data of the attachment--but my computer can't open the attachments I'm sending.)
At any rate I believe this is the way to do it, and certainly I have been able to send messages with attachments with it.

Categories