i have the following function:
public function getMails()
{
$mails = array();
$numMessages = imap_num_msg($this->imap);
for ($i = 1; $i <= $numMessages; $i++)
{
$header = imap_header($this->imap, $i);
$fromInfo = $header->from[0];
$replyInfo = $header->reply_to[0];
$details = array(
"fromAddr" => (isset($fromInfo->mailbox) && isset($fromInfo->host))
? $fromInfo->mailbox . "#" . $fromInfo->host : "",
"fromName" => (isset($fromInfo->personal))
? $fromInfo->personal : "",
"replyAddr" => (isset($replyInfo->mailbox) && isset($replyInfo->host))
? $replyInfo->mailbox . "#" . $replyInfo->host : "",
"replyName" => (isset($replyInfo->personal))
? $replyInfo->personal : "",
"subject" => (isset($header->subject))
? $header->subject : "",
"udate" => (isset($header->udate))
? $header->udate : ""
);
$bodyText = imap_fetchbody($this->imap,$i,1.2);
if(!strlen($bodyText)>0){
$bodyText = imap_fetchbody($this->imap,$i,1);
}
$details['body'] = $bodyText;
$uid = imap_uid($this->imap, $i);
$current_mail = array('header'=>$header, 'from'=>$fromInfo, 'reply'=>$replyInfo, 'details'=>$details);
$mails[$i] = $current_mail;
}
}
However there is a problem with the body text.
This is a test mail that i sendt from my email that looks like this:
Hello world
Med venlig hilsen
Marc Rasmussen
Besøg mig på MarcRasmussen.dk
However the body text is looks like this when taken from imap:
Hello world=0A=
=0A=
Med venlig hilsen=0A=
=0A=
Marc Rasmussen=0A=
=0A=
Bes=F8g mig p=E5 MarcRasmussen.dk =
is there any buildin method in PHP to fix this issue?
You have to check the Content-Transfer-Encoding header of the MIME part you are working on (hint: it's available in IMAP's BODYSTRUCTURE) and decode it yourself. The two most common encoding are quoted-printable and base64. See RFC 2045, chapter 6 for details.
You could try to use the $options parameter of the imap_fetchbody function. Maybe with flag FT_INTERNAL combined with utf8_encode:
$bodyText = utf8_encode(imap_fetchbody($this->imap,$i,1, FT_INTERNAL));
I hope it works for you!
Related
How to format Whatsapp Web Message ?
I trying replacing tags like this :
$nl = "%0D%0A";
$space = "%20";
$MSG = nl2br($MSG);
$MSG = str_replace( array("<b>","<bold>","</b>","</bold>"), array("*","*","*","*"), $MSG);
$MSG = str_replace( array(" ","<br>","\n", "\r\n"), array($space,$nl,$nl,$nl), $MSG);
I tried using urlencode, htmlspecialchars and nothing.
I´m receiving on https://api.whatsapp.com/send?phone=XXX&text=MSG a totally unformated and with a lot of chars string. Like this :
%F0%9F%94%94%2A...
I found the error and I´m posting here to help others.
// Should use UTF8
$MSG = utf8_encode($MSG);
// Whatsapp patterns
$nl = "%0D%0A"; // newline
$space = "%20"; // space
// Replace some Whatstapp tags
$MSG = str_replace( array("<b>","<bold>","</b>","</bold>"), array("*","*","*","*"), $MSG);
// Replace newline to Whatsapp format
$MSG = str_replace( array(" ","<br>","\n", "\r\n"), array($space,$nl,$nl,$nl), $MSG);
I replace only BOLD but you can add others tags. See :
https://faq.whatsapp.com/general/chats/how-to-format-your-messages/?lang=en
I'm trying to set Google Translation API on my server.
But code returns error "Could not construct ApplicationDefaultCredentials"
$translationClient = new Google\Cloud\Translate\V3\TranslationServiceClient();
putenv('GOOGLE_APPLICATION_CREDENTIALS="/path/to/credetials.json"');
$content = ['one', 'two', 'three'];
$targetLanguage = 'es';
$response = $translationClient->translateText(
$content,
$targetLanguage,
TranslationServiceClient::locationName('[ProjectID]', 'global')
);
$res = '';
foreach ($response->getTranslations() as $key => $translation) {
$separator = $key === 2
? '!'
: ', ';
$res .= $translation->getTranslatedText() . $separator;
}
} catch(\Exception $e) {
$res = $e->getMessage();
}
die(json_encode($res));
I've already spend a lot of time to setting it but with no result.
Please, help me
You can pass the credentials in a config variable and then initialize the client.
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Translate\V2\TranslateClient;
/** Uncomment and populate these variables in your code */
$config = ['credentials' => 'key.json'];
$text = "The text to translate.";
$targetLanguage = "ja";
$translate = new TranslateClient($config);
$result = $translate->translate($text, [
"target" => $targetLanguage,
]);
print("Source language: $result[source]\n");
print("Translation: $result[text]\n");
?>
Source language: en
Translation: 翻訳するテキスト
Php putenv https://www.php.net/manual/en/function.putenv.php
Andrey this worked for me on Windows 10 Pro. Wampserver 3.2.0. Php 7.4.4. It definitely has a problem with Windows backslashes. Forwardslashes and avoiding double quotes and single quotes together has helped to bump the compiler along.
$file = trim("C:/users/boss/onedrive/desktop/google.json",'"');
putenv("GOOGLE_APPLICATION_CREDENTIALS=$file");
I have a problem with Swift Mailer, It seems easy, but I'm strugling with it for hours.
I need to send an email to multiple recipients.
This is a string I begin with (the content of $email->getRecipients() ):
// Just an example
first#gmail.com, second#gmail.com
First I remove all non-visible characters:
$string = preg_replace('/[\x00-\x1F\x7F]/u', '', $email->getRecipients());
Then I add surranding quotes:
$addQuotes = "'" . str_replace(",", "','", $string) . "'";
And remove empty spaces:
$recipients = str_replace(' ', '', $addQuotes);
Which gives me:
'first#gmail.com','second#gmail.com'
If I paste the string manually:
->setTo(['first#gmail.com','second#gmail.com'])
It works. But when I try to put variable like this:
$array = explode(',', $recipients);
...
->setTo($array)
Emails are not being sent.
When I do this:
->setTo([$recipients])
I get the error Address in mailbox given ['...','...'] does not comply with RFC 2822, 3.6.2.
I also tried:
foreach($array as $recipient) {
$message->setTo($recipient);
$this->get('mailer')->send($message);
}
Not working! But again, if I paste string directly, it works:
foreach($array as $recipient) {
$message->setTo('first#gmail.com');
$this->get('mailer')->send($message);
}
The code:
private function sendEmail($email)
{
//$email->getRecipients() = 'first#gmail.com, second#gmail.com'
$string = preg_replace('/[\x00-\x1F\x7F]/u', '', $email->getRecipients());
$addQuotes = "'" . str_replace(",", "','", $string) . "'";
$recipients = str_replace(' ', '', $addQuotes);
$array = explode(',', $recipients);
$message = \Swift_Message::newInstance()
->setSubject($email->getSubject())
->setFrom($email->getSender())
->setTo($array)
->setBody(
$this->renderView(
'Emails/default.html.twig',
array('body' => $email->getBody())
),
'text/html'
);
//foreach($array as $recipient) {
// $message->setTo($recipient);
// $this->get('mailer')->send($message);
//}
$this->get('mailer')->send($message);
}
I have a question. I send out an E-Mail via "PHPMailer" Class. Then I answered with Outlook 2013 to this mail. Afterwords im Trying to read the Email via PHP with "imap_fetchbody". But I only get
PGh0bWwgeG1sbnM6dj0idXJuOnNjaGVtYXMtbWljcm9zb2Z0LWNvbTp2bWwiIHhtbG5zOm89InVy bjpzY2hlbWFzLW1pY3Jvc29mdC1jb206b2ZmaWNlOm9mZmljZSIgeG1sbnM6dz0idXJuOnNjaGVt YXMtbWljcm9zb2Z0LWNvbTpvZmZpY2U6d29yZCIgeG1sbnM6bT0iaHR0cDovL3NjaGVtYXMubWlj cm9zb2Z0LmNvbS9vZmZpY2UvMjAwNC8xMi9vbW1sIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcv VFIvUkVDLWh0bWw0MCI+DQo8aGVhZD4NCjxtZXRhIGh0dHAtZXF1aXY9IkNvbnRlbnQtVHlwZSIg Y29udGVudD0idGV4dC9odG1sOyBjaGFyc2V0PXV0Zi04Ij4NCjxtZXRhIG5hbWU9IkdlbmVyYXRv ciIgY29udGVudD0iTWljcm9zb2Z0IFdvcmQgMTUgKGZpbHRlcmVkIG1lZGl1bSkiPg0KPCEtLVtp ZiAhbXNvXT48c3R5bGU+dlw6KiB7YmVoYXZpb3I6dXJsKCNkZWZhdWx0I1ZNTCk7fQ0Kb1w6KiB7 YmVoYXZpb3I6dXJsKCNkZWZhdWx0I1ZNTCk7fQ0Kd1w6KiB7YmVoYXZpb3I6dXJsKCNkZWZhdWx0 I1ZNTCk7fQ0KLnNoYXBlIHtiZWhhdmlvcjp1cmwoI2RlZmF1bHQjVk1MKTt9DQo8L3N0eWxlPjwh W2VuZGlmXS0tPjxzdHlsZT48IS0tD[...]
Stuff like this - I tried many decoding options in the imap_fetchbody function, but I am not getting it - this is my code:
$server='{IPADDRESS:143/novalidate-cert}INBOX';
$adresse='cloud#MYDOMAIN';
$password='MYPASSWORD';
$mbox = imap_open($server, $adresse, $password, OP_READONLY, 1, array('DISABLE_AUTHENTICATOR' => 'PLAIN')) or die(var_dump(imap_errors()));
$no = 1;
$headers = imap_headers($mbox);
$text = imap_fetchbody($mbox, $no, 1);
for($i = 0; $i < count($headers); ++$i)
{
$string = imap_fetchbody($mbox, $i+1, 1);
echo $string;
}
Any Ideas?
I found a solution myself. It seems that those messages come with different Mime Types, etc. So this function helps to find the mime type and offers an easy "getBody" function - see this page:
https://www.sitepoint.com/exploring-phps-imap-library-1/
I can now send an SMS via kannel. However this is done via headers eg:
header("Location:http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
I want to send an sms via a php function and I got the code below online but it doesn't work. (Kannel smsbox log shows no request):
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&coding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
$results = file('http://'
. CONFIG_KANNEL_HOST . ':'
. CONFIG_KANNEL_PORT . $url);
}
Is there something wrong? I tried replacing the CONFIG_KANNEL_USER_NAME and the rest with the actual values but it still doesn't work. Open to suggestions.
I used cURL and it works 100% okay. file_get_contents does not work for me because I want to pass variables to the kannel url and file_get_contents does not process variables coz it insists on using single quotes(php treats it as a string value) instead of double quotes(php will parse the string checking for variables etc).
Here is what i am currently doing assuming you already have your variables initialized somewhere:
$textmsg="Hello Stackoverflow Users!";
$cellphone_number = "+254xxxxxxx"
$encmsg=urlencode($textmsg);
$ch= curl_init();
curl_setopt($ch, "http://localhost:13013/cgi-bin/sendsms?username=xxxxx&password=xxxxx&to=$cellphone_number&text=$encmsg");
curl_exec($ch);
curl_close($ch);
This will work for the simple task of telling kannel to send an sms to a number. Took me a while to realize curl does not recognize spaces and special characters :-).
My friend and I from Ndola, Zambia are using ubuntu 11.04 to run kannel_1.4.3. It works perfectly way in sending and receiving sms. The code below had to be edited for it to send more that 70 characters. My friend and I struggled to figure out that there was a small error in the line '&charset=UCS-2&coding=2'. The correct line should be '&charset=UCS-2&encoding=2'. So the code should appear as below:
function sendSmsMessage($in_number, $in_msg)
{
$url = '/cgi-bin/sendsms?username=' . CONFIG_KANNEL_USER_NAME
. '&password=' . CONFIG_KANNEL_PASSWORD
. '&charset=UCS-2&encoding=2'
. "&to={$in_number}"
. '&text=' . urlencode(iconv('utf-8', 'ucs-2', $in_msg));
Using curl:
curl_init("http://$gw_host:$gw_port/cgi-bin/sendsms?username=$gw_user&password=$gw_pass&to=$to&from=$shortcode&smsc=$smsc&dlr-mask=$dlrmask&binfo=$shortcode&text=$message");
Replace the various variables/parameters with your values such as:
$gw_host=127.0.0.1
$gw_port=13xx3
etc.
If you're attempting to trigger a URL loading in the background (rather than by re-directing the user to the URL), you need to use something like cURL or perhaps even file_get_contents.
For example, if your set up has fopen URL wrappers enabled, you could simply use:
$response = file_get_contents("http://localhost:13013/cgi-bin/sendsms?username=xxxx&password=xxxx&to=$in_number&text=$in_msg");
Irrespective, it's hard to know why the function you found won't work without some additional debug information. (If CONFIG_KANNEL_HOST is defined as "localhost" and CONFIG_KANNEL_PORT is defined as 13013 then it's effectively doing the same thing, albeit with additional character set operations.)
Not to ressucitate an ancient question, but for posteriority and others searching for the same thing:
[root#sat2 tools]# cat kannel-send.php
<?php
function send_sms($msgid, $numto, $msgtext, $smsc = "smsc-default", $dlrmask = 63)
{
$sendsmsurl_prefix = "http://localhost:13013/cgi-bin/sendsms";
$dlrurl_prefix = "http://localhost/tools/kannel-receive.php";
$username = "user";
$password = "pass";
# fix number to what carriers expect
$numto = preg_replace('/^0/', '', $numto);
$numto = preg_replace('/^\+55/', '', $numto);
$numto = "0" . $numto;
if (!$msgid) $dlrmask = 0;
$dlrurl_params = array(
"type" => "dlr",
"timesent" => "%t",
"smsc" => "%i",
"uuid" => "%I",
"fid" => "%F",
"dlr-cod" => "%d",
"reply" => "%A",
"msgid" => $msgid,
"text" => "%a",
"to" => "%P",
"from" => "%p",
"origsmsc" => "%f",
);
$dlrurl = $dlrurl_prefix . "?" . urldecode(http_build_query($dlrurl_params));
$sendsmsurl_params = array(
"username" => $username,
"password" => $password,
"to" => $numto,
"dlr-mask" => $dlrmask,
"dlr-url" => $dlrurl,
"smsc"=> $smsc,
"text" => $msgtext,
);
$sendsmsurl = $sendsmsurl_prefix . "?" . http_build_query($sendsmsurl_params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sendsmsurl);
$bogus = curl_exec($ch);
$ret = curl_error($ch);
curl_close($ch);
return $ret == "";
}
?>
And you could have this other one to receive sms and store it to mysql:
[root#sat2 tools]# cat kannel-receive.php
<?php
$debug = false;
$link = null;
function dbconnect()
{
global $link, $debug;
if ($link && mysql_ping($link))
return;
if ($debug) echo "Conectando ao banco de dados\n";
// TODO: criar um usuario de banco especifico pra isso
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'dbname';
$link = mysql_connect($host, $user, $pass, true);
if (!$link){
if ($debug) echo "Can't connect to mysql: " . mysql_error() . "\n";
} else {
mysql_select_db($db, $link);
}
return;
}
function esc($str)
{
global $link;
return mysql_real_escape_string($str, $link);
}
if ($debug) {
echo "<br>Kannel inbound sms event:<br>\n";
var_dump($_GET);
}
dbconnect();
if ($_GET['type'] == "inbsms") {
$_GET['from'] = preg_replace('/^(\+55|0)/', '', $_GET['from']);
$sql = "INSERT INTO notificacao (tipo, endereco, mensagem, device,
dataEvento, situacao)
VALUES ('%s', '%s','%s','%s','%s','%s')";
$sql = sprintf($sql, 'sms', esc($_GET['from']), esc($_GET['text']),
esc($_GET['smsc']), esc($_GET['timesent']), "received");
} elseif ($_GET['type'] == "dlr") {
switch (esc($_GET['dlr-cod'])) {
case "1":
$sql = "UPDATE notificacao SET
situacao = 'confirmed',
dataConfirmacao = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "8":
$sql = "UPDATE notificacao SET
situacao = 'sent',
device = '{$_GET['smsc']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
case "16":
$sql = "UPDATE notificacao SET
situacao = 'failed',
device = '{$_GET['smsc']}',
razaofalha = '{$_GET['reply']}',
dataEvento = '{$_GET['timesent']}'
WHERE idnotificacao = {$_GET['msgid']}";
break;
}
}
if ($debug) echo "sql: $sql\n";
$result = mysql_query($sql, $link);
if (!$result) {
if ($debug) echo "Erro sql: " . mysql_error() . "\n";
}
?>
This one doubles as a SMS receiver and a SMS-Delivery-Notification receiver (in that case it updates a record on the database that was put there when sending the sms, to confirm it was received).
It's used for DLR because I send the URL for that when sending the SMS (and set the DLR mask asking for confirmation), but for inbound SMS you have to configure your kannel.conf to use it (you can have many sms-service, this is just an example of a catch-all one:
[...]
group = sms-service
keyword = default
get-url = "http://localhost/tools/kannel-receive.php?type=inbsms&text=%a×ent=%t&from=%p&to=%P&smsc=%i&uuid=%I&delivery=%d&service=%n&encoding=%c&class=%m&mwi=%M&charset=%C&udh=%u&dcs=%O&origsmsc=%f"
catch-all = yes
max-messages = 0
accept-x-kannel-headers = true
concatenation = yes
omit-empty = yes
[...]
Sorry for some texts in portuguese, but you can get the picture.
//php code file name is test2.php.before that,you must install php5-curl on ubuntu14