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.
Related
I have created a custom registration form in Drupal 8, and now i want to sent a mail from the submission of the form. So I have did it like this
This is my .module file
/**
* Implements hook_mail().
*/
function Registration_form_mail($key, &$message, $params) {
$options = array(
'langcode' => $message['langcode'],
);
switch ($key) {
case 'contact_form':
$message['from'] = \Drupal::config('system.site')->get('mail');
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
public function submitForm(array &$form, FormStateInterface $form_state){
$mailManager = \Drupal::service('plugin.manager.mail');
$module = 'Registration_form';
$key = 'contact_form'; // Replace with Your key
$to = $form_state->getValue('Email');
$params = array(
'body' => 'test',
'subject' => 'Website Information Request',
);
$langcode = \Drupal::currentUser()->getPreferredLangcode();
$send = true;
$message['subject'] = t('nouveau contact ');
$message['body'][] = t('test');
$result = $mailManager->mail($module, $key, $to, $langcode, $params, NULL, $send);
if ($result['result'] != true) {
$message = t('There was a problem sending your email notification to #email.', array('#email' => $to));
drupal_set_message($message, 'error');
\Drupal::logger('mail-log')->error($message);
return;
}
else{
$message = t('An email notification has been sent to #email ', array('#email' => $to));
drupal_set_message($message);
\Drupal::logger('mail-log')->notice($message);
}
}
So my question is i'm using localhost in xampp and i want to sent a mail after submission of the form, but i'm getting this error
Unable to send email. Contact the site administrator if the problem persists.
There was a problem sending your email notification to ABC#gmail.com
So how I can resolve my problem, i have gone through whole sites but not able to find answer.
The problem may be with the email configuration. See if this article helps you:
https://stevepolito.design/blog/drupal-configure-smtp-module-work-gmail-updated/
I am using twilio to send sms to mobile, when i run the script it sends an SMS like it should to my mobile but the problem is i don't know the status of the sent SMS, how do i get that?
What i tried so far is below
<?php
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
// Your Account SID and Auth Token from twilio.com/console
$account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$auth_token = 'your_auth_token';
// In production, these should be environment variables. E.g.:
// $auth_token = $_ENV["TWILIO_ACCOUNT_SID"]
// A Twilio number you own with SMS capabilities
$twilio_number = "+0987654321";
$client = new Client($account_sid, $auth_token);
$client->messages->create(
// Where to send a text message (your cell phone?)
'+1234567890',
array(
'from' => $twilio_number,
'body' => 'I sent this message in under 10 minutes!'
)
);
after doing proper research, and having all kind of issues with the webhook, here is what i settled on
$phoneString = $phoneNumber->asNorthAmericanDialingString();
$mi = $client->messages->create(
// the number you'd like to send the message to
$phoneString ,
array (
// A Twilio phone number you purchased at twilio.com/console
'from' => Config::getCurrentConfig()->smsConfig->fromNumber ,
// the body of the text message you'd like to send
'body' => $message ,
'ProvideFeedback' => "true"
)
);
$msg = $mi->fetch();
$sid = $msg->sid;
$status = $msg->status;
if ($status == 'sent' || $status == 'delivered') { // f'ing twilio, random status
self::getClassLogger()->debug("Sent text message[$sid], status is [$status]");
return new TextMessageStatus($sid , $status);
} else {
// do whatever is appropriate for your case
}
I'm trying to do some SMS messages using Twilio, and so far it's pretty straight forward, but I'm using some test data to capture various scenarios and I used "1234567890" as a phone number to capture an error, but I get the following error when I navigate to the page that queries the twilio api:
Fatal error: Uncaught exception 'Twilio\Exceptions\RestException'
with message '[HTTP 404] Unable to fetch record:
The requested resource /PhoneNumbers/1234567890 was not found'
Here's my code:
use Twilio\Rest\Client;
$client = new Client($sid, $token);
if($ph && preg_match('/^[0-9]{10}$/', $ph)) {
//this returns an array containing type, error_code, and a boolean
//value for is_valid.
$response = lookup($client, $ph);
if($response['is_valid']) {
//send the message via twilio.
$message = $client->messages->create(
$ph,
array(
'from' => 'my_twilio_number_goes_here',
'body' => 'text_body_goes_here'
)
);
//handle twilio response
$status = $message->status;
$sid = $message->sid;
}
How can I capture that response?
$twilio = new TwilioClient(env('TWILIO_ACCOUNT_ID'), env('TWILIO_TOKEN'));
$message=new \StdClass;
try
{
//check mobile number is valid or not
$is_valid_number = $twilio->lookups->v1->phoneNumbers($phone_number)->fetch();
if($is_valid_number)
{
$data['From']=env('TWILIO_FROM_ALPHANUMERIC_NAME');
$data['Body']="Sms testing";
$message = $twilio->messages->create($mobile_number, $data);
}
else{
echo "Your Mobile number is not available.";
}
}
catch(\Exception $e)
{
echo $e->getMessage();
}
$to=+11111111;
$body="hello Its not working";
$AccountSid = "*********************************";
$AuthToken = "*********************************";
$client = new Services_Twilio($AccountSid, $AuthToken);
$from = '+11111111';
$message = $client->account->sms_messages->create($from, $to, $body);
return true;
It is working on normal server but not on amazon server.
when i comment $message the code loads the page properly and when uncomment the $message, it just keeps on loading (i.e. the loading circle keeps on rolling not opens any page).
I am receiving both the numbers and the text message too thats not an issue but the $client->account->sms_messages->create() not working.
Someone help!
If you give "+11111111111" as from number. Twilio will show the error
Fatal error: Uncaught exception 'Services_Twilio_RestException' with message 'The 'From' number 11111111111 is not a valid phone number or shortcode.
So you should add valid twilio number that exist in your twilio account as from number. Then try this.
$sms = $client->account->messages->create(array(
'To' => "$toNumber",
'From' => "$myNumber",
'Body' => "$msg"));
}
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.