I'm trying to develop a web application that send email throught Gmail API.
But I'm getting this error :
Call to undefined method Google_Service_Gmail_Message::toSimpleObject()
Here is my code :
// LOAD GOOGLE LIBRARY
$this->CI->load->library('master_google');
$this->CI->load->library('master_phpmailer');
$client = $this->CI->master_google->getClient($data);
$mail = $this->CI->master_phpmailer;
$mail->setFrom($data->sender_email, $data->sender_name);
$mail->addReplyTo($data->response_email, $data->response_name);
$mail->addAddress($data->email);
$mail->Subject = $data->subject;
$mail->msgHTML(htmlspecialchars_decode($data->body));
$mail->preSend();
$mime = $mail->getSentMIMEMessage();
$encoded_message = base64url_encode($mime);
// Gmail Message Body
**$message = new Google_Service_Gmail_Message();**
$message->setRaw($encoded_message);
// Send the Email
$service = new Google_Service_Gmail($client);
$email = $service->users_messages->send('me',$message);
if($email->getId()){
return array('stat' => true, 'msg' => '');
} else {
return array('stat' => false, 'msg' => '');
}
The error is generated on this line :
$message = new Google_Service_Gmail_Message();
Any help is appreciated.
I found what was the problem lol, I had a model with the same name : Google_model, I rename that to Mygoogle_model and it works :D
I think the method toSimpleObject() does not exist in your gmail-api class.
Related
when I try to send a whatsapp message to a mobile number that isn't registered on whatsapp, how do I know that it failed? because I want to send the message using regular SMS instead. but my code below doesn't give any different result between success and failed process:
public function sendMessage($to, $msg, $params=[])
{
$client = new Client($this->sid, $this->token);
$from = $this->from_number; // my twilio number e.g. +1786xxxx
if ( ! empty($params['via']) && $params['via'] == 'whatsapp') {
$to = 'whatsapp:'.$to;
$from = 'whatsapp:'.$from;
}
$options = [
// A Twilio phone number you purchased at twilio.com/console
'from' => $from,
// the body of the text message you'd like to send
'body' => $msg,
];
// Use the client to do fun stuff like send text messages!
$response = $client->messages->create(
$to,
$options,
);
return $response;
}
// end public function sendMessage
public function do_send_msg()
{
$to = '+628123456789';
// this message already uses the same format as the approved message template
$msg = "Your otp code for Login Process is 123456";
$params = [
'via' => 'whatsapp',
];
$send = $this->twilio->sendMessage('+628123456789', $msg, $params);
var_dump($send->status);
}
I wanted to make the code like this instead but this code is unable to differentiate the value of $send->status whether it's successful or failed:
public function do_send_msg()
{
$to = '+628123456789';
// this message already uses the same format as the approved message template
$msg = "Your otp code for Login Process is 123456";
$params = [
'via' => 'whatsapp',
];
$send = $this->sendMessage($to, $msg, $params);
// if sending via whatsapp failed, try sending via regular SMS instead
if ( ! $send->status ) {
$params['via'] = 'SMS';
$send = $this->sendMessage($to, $msg, $params);
}
}
I'm afraid Meta/WhatsApp doesn't expose this information at this point in time. Therefore, I'd recommend that you let the users choose whether they want to receive a WhatsApp message or a regular SMS.
I'm trying to create an email with php in Dynamics 365 by using the AlexaCRM php-crm toolkit after someone fills in the form on our website.
The email also appears in Dynamics, but the from and to fields are empty. The email itself and the subject are stored in Dynamics.
Does anyone had the same problem or does anyone knows what I'm doing wrong?
This is the code I'm using.
<?php
require_once '../vendor/autoload.php';
use AlexaCRM\CRMToolkit\Client as OrganizationService;
use AlexaCRM\CRMToolkit\Settings;
use AlexaCRM\CRMToolkit\Client;
use AlexaCRM\CRMToolkit\Entity\MetadataCollection;
use AlexaCRM\CRMToolkit\Entity\EntityReference;
$options = [
'serverUrl' => 'xxx.dynamics.com',
'username' => 'xxx#xxx.com',
'password' => 'xxxxxx',
'authMode' => 'OnlineFederation',
];
$serviceSettings = new Settings( $options );
$service = new OrganizationService( $serviceSettings );
$email = $service->entity( 'email' );
$email->subject = 'TEST SUBJECT';
$email->description = 'TEST EMAIL';
$email->sender = 'Sender Name';
$email->from = 'test#gmail.com';
$email->to = 'Our Company';
$email->torecipients = 'test#ourcompany.com';
$emailId = $email->create();
?>
Thanks for your help.
I created activityparties, but it still doesn"t write the email correctly to Dynamics.
I don't know how to combine the two parties.
This is my code:
$to = $service->entity( 'activityparty' );
$to->partyid = new EntityReference( 'systemuser', ''.$guid_stassen.'');
$from = $service->entity( 'activityparty' );
$from->partyid = new EntityReference( 'contact', ''.$guid.'');
$email = $service->entity( 'email' );
$email->subject = 'TEST SUBJECT';
$email->description = 'TEST EMAIL';
$email->from = ''.$from.'';
$email->to = ''.$to.'';
$emailId = $email->create();
rather than
$email->from = ''.$from.'';
$email->to = ''.$to.'';
you will have to use email_activity_parties as an array. I am not familair with PHP but something like below
$email->email_activity_parties=[
{
"partyid_systemuser#odata.bind" : "/systemusers(CED2E02D-188E-4AA8-B6E2-D746E9B370C1)",
"participationtypemask" : 1
},
{
"addressused":"vvyas#cloudfronts.com",
"participationtypemask" : 2
}
];
This happens because To and From field is not text field rather it is Party list field.
you cannot directly add/put email address, you will need to create object with it's type and email address.
Take a look at this blog, it has all the information you need.
Below sample for To and from, but here these are users in system.
"email_activity_parties" : [
{
"partyid_systemuser#odata.bind" : "/systemusers(CED2E02D-188E-4AA8-B6E2-D746E9B370C1)",
"participationtypemask" : 1 ///From Email
},
{
"partyid_account#odata.bind" : "/accounts(69C38067-EDB7-E811-A961-000D3A363C81)",
"participationtypemask" : 2 ///To Email
}]
Creating Email with unresolved emails (To field of email is not record in MS CRM).
"email_activity_parties" : [
{
"partyid_systemuser#odata.bind" : "/systemusers(CED2E02D-188E-4AA8-B6E2-D746E9B370C1)",
"participationtypemask" : 1 ///From Email
},
{
"addressused":"vvyas#cloudfronts.com",
"participationtypemask" : 2 ///To Email
}
]
I'm using Zapier to collect leads from facebook,and than send them to my CRM.
I Have a script connected to my CRM,that is supposed to handle the leads.
for every new lead the script will trigger,
the script collects the data passed from Zapier and converts it to an XML and sends it my client.
Everything works except for one thing.
The PHPMailer seems to cause trouble with zapier,because whenever the email() function is enabled Zapier will give me an Error.
FYI - this works when I go to the script url and set the GET parameters by hand .
the xml is being sent. But when triggering the script from zapier the problem occurs.
Zapier Error:
"We had trouble sending your test through.
The app returned "Internal Server Error" with no further details. It looks like the server for your connected app is down or currently experiencing problems. Please check the app's status page or contact support if there are no reported issues."
<?php
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
$lastName = isset($_GET['lastName']) ? $_GET['lastName'] : '';
$fullName = isset($_GET['fullName']) ? $_GET['fullName'] : '';
$phone = isset($_GET['phone']) ? $_GET['phone'] : '';
$experience = isset($_GET['experience']) ? $_GET['experience'] : '';
$city = isset($_GET['city']) ? $_GET['city'] : '';
$email = isset($_GET['email']) ? $_GET['email'] : '';
$utm_source = isset($_GET['utm_source']) ? $_GET['utm_source'] : '';
$campaignId = isset($_GET['campaignId']) ? $_GET['campaignId'] : '';
$utm_medium = isset($_GET['utm_medium']) ? $_GET['utm_medium'] : '';
require 'vendor/autoload.php';
header('Content-Type: text/plain');
function createXML($data,$dataSource){
$dom = new DOMDocument('1.0', 'utf-8');
$cv = $dom->createElement("cv");
$candidate = $dom->createElement('candidate');
$source_type = $dom->createElement('source_type');
function recursive($dom, $parent, $key, $value) {
if(is_array($value)) {
$new_parent = $dom->createElement($key);
foreach($value as $k => $v){
recursive($dom, $new_parent, $k, $v);
}
$parent->appendChild($new_parent);
} else {
$field = $dom->createElement($key, htmlspecialchars($value));
$parent->appendChild($field);
}
}
foreach($dataSource as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $source_type, $key, $value);
}
foreach($data as $key => $value){
// api need COLUMN without end of _<number>
if(preg_match('/COLUMN_([0-9]+)/', $key)) $key = 'COLUMN';
recursive($dom, $candidate, $key, $value);
}
// $cv->appendChild($candidate)
$cv->appendChild($candidate);
$cv->appendChild($source_type);
$dom->appendChild($cv);
$node = $cv->appendChild($source_type);
$node->setAttribute('type','other');
$dom->formatOutput = true;
return $dom;
}
$data = array(
"first_name" => filter_var($firstName, FILTER_SANITIZE_STRING),
"last_name" => filter_var($lastName, FILTER_SANITIZE_STRING),
"mobile" => filter_var($phone, FILTER_SANITIZE_STRING),
'email' => '',
'id' => '',
);
$dataSource = array(
"source_title" => filter_var($utm_source, FILTER_SANITIZE_STRING),
"first_name" => '',
"last_name" => '',
"mobile" => '',
"email" => '',
"employee_number" => '',
"department" => '',
"email" => '',
);
//problematic function
function email(){
global $xmlData;
$mail = new PHPMailer(true);
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - " . $today;
}
///////// IF I uncomment bellow,Zapier will give me the following error:
//We had trouble sending your test through.
//The app returned "Internal Server Error" with no further details.
//It looks like the server for your connected app is down or currently experiencing problems.
//Please check the app's status page or contact support if there are no reported issues.
//Uncomment bellow.
// email();
?>
I Expect for every Lead to send an email containing a XML.
Two key problems. Firstly, you're using SMTP, but you have not set Host to your mail server - so it won't work unless it's localhost - is that the case?
You're asking PHPMailer to throw exceptions (by passing true to the constructor), but you don't have a try/catch block wrapped around the calls to PHPMailer, so any errors will result in uncaught exceptions - which will give you exactly the symptom you're seeing. Try this:
function email()
{
global $xmlData;
$mail = new PHPMailer(true);
try {
$mail->isHTML(false);
$mail->isSMTP();
$mail->setFrom('XML#gmail.com', 'Yashir CV Lead');
$mail->addAddress("BinaryRx#gmail.com");
$mail->Subject = "Yashir CV Lead";
$mail->Body = $xmlData;
$today = date('d-m-Y H:i:s');
$mail->send();
echo "Report Sent - ".$today;
} catch (Exception $e) {
echo 'Sending failed'.$e->getMessage();
}
}
Overall, the main thing is to debug one thing at a time - check that the email() function actually works independently before you start trying to do things that depend on it working, because otherwise you won't know which bit of the code is failing.
If you're using PHP 7.0 or later, you can simplify those initial checks for params by using the null coalesce operator. You can replace this:
$firstName = isset($_GET['firstName']) ? $_GET['firstName'] : '';
with:
$firstName = $_GET['firstName'] ?? '';
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.
I am trying to get this mail sent on registration using SwiftMailer, however it keeps throwing this error.
I am using this add-on for osCommerce:
http://addons.oscommerce.com/info/901
I have followed the exact instructions as per what he said. Also added permissions still the same thing.
I am posting the code below:
CODE:
if (EMAIL_TRANSPORT == 'smtp') {
include_once(DIR_FS_CATALOG.DIR_WS_CLASSES . 'SwiftEmailer/swift_required.php');
$body = $this->html;
$body = preg_replace("[]",'',$body);
$host_name = explode('://',EMAIL_SMTP_HOST_SERVER);
if(count($host_name)>1){
$transport = Swift_SmtpTransport::newInstance($host_name[1], EMAIL_SMTP_PORT_SERVER, $host_name[0])
->setUsername(EMAIL_SMTP_USERNAME)
->setPassword(EMAIL_SMTP_PASSWORD);
} else {
$transport = Swift_SmtpTransport::newInstance(EMAIL_SMTP_HOST_SERVER, EMAIL_SMTP_PORT_SERVER)
->setUsername(EMAIL_SMTP_USERNAME)
->setPassword(EMAIL_SMTP_PASSWORD);
}
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance($subject)
->setFrom(array($from_addr => $from_name))
->setTo(array($to_addr => $to_name))
->setMaxLineLength(50);
if($body){
$message->setBody($body, 'text/html', CHARSET);
}
if($this->text){
$message->setBody($this->text, 'text/plain', CHARSET);
}
else{
$message->setBody($this->html_text, 'text/html', CHARSET);
}
$mailer->send($message);
}
If anyone could help me sort out this issue that would be great. Thank you