Searching email body without downloading - IMAP - php

Can I search ALL emails over IMAP without downloading the message(s)?
As specified in 6.4.4 of RFC 3501 IMAP version 4 revision 1 (IMAP4rev1):
The SEARCH command searches the mailbox for messages that match
the given searching criteria. Searching criteria consist of one
or more search keys. The untagged SEARCH response from the server
contains a listing of message sequence numbers corresponding to
those messages that match the searching criteria.
The defined search keys are as follows. Refer to the Formal
Syntax section for the precise syntactic definitions of the
arguments
BODY
Messages that contain the specified string in the body of the
message.
...so I wonder if I can search inside the body of the email without downloading it first?

The function imap_search() could help you but have in mind that it needs to be supported by the IMAP server to work.
UPDATE:
This is the small program:
error_reporting(E_ALL);
ini_set('display_errors', '1');
$user = ''; // put your Gmail email address here (including '#gmail.com');
$pass = ''; // put your Gmail password here
$host = 'imap.gmail.com:993'; // Put your IMAP server here with portGmail
$keyword = ''; // put the word you want to find
$mailbox = sprintf('{%s/imap/ssl/user=%s}INBOX', $host, $user);
$query = sprintf('BODY "%s"', $keyword);
$mbox = imap_open($mailbox, $user, $pass, OP_READONLY);
if ($mbox) {
$list = imap_search($mbox, $query, SE_UID);
var_dump($list);
imap_close($mbox);
}
It may or may not work with your setup. It worked for me with one account on our company mail server. It failed to connect on another server that works fine with my regular email client.
It worked and failed on the same time (!!) with Gmail. Don't ask!

Related

How do I code in PHP this instruction provided by a vendor "DELETE /<domain>/unsubscribes/<address>"

I am working with Mailgiun. Their documentation shows a php example for obtaining a list of email addresses (see below), which I have working in my own code.
require 'vendor/autoload.php';
use Mailgun\Mailgun;
# Instantiate the client.
$mgClient = Mailgun::create('PRIVATE_API_KEY', 'https://API_HOSTNAME');
$domain = 'YOUR_DOMAIN_NAME';
$recipient = 'bob#example.com';
$tag = '*';
# Issue the call to the client.
$result = $mgClient->suppressions()->unsubscribes()->create($domain, $recipient, $tag);
I want to remove an entry in their list, and their code example for doing so only shows the following line of code:
DELETE /<domain>/unsubscribes/<address>
How do I code the line above using PHP?
Note:
I have tried the following block of code,
$result = $mailgun_client->suppressions()->bounces()->delete('mg.quikkast.com', 'emailaddress#gmail.com');
but get back a the following error:
Mailgun\Exception\HttpClientException: The endpoint you have tried to access does not exist. Check if the domain matches the domain you have configure on Mailgun.
Thus far Mailgun has not responded with a solution to my support ticket. So any help would be greatly appreciated.
Upgraded to latest version of MG library. Posted a new question to specifically get MG to correct error their code is reporting.

Getting Plesk Mailbox information with PHP?

I have set some mail quota's on email addresses that I manage through Plesk.
However, users are complaining that they are not being informed when their inbox is full or nearly full.
So my idea was to send an email to them when their inbox is about 90% full, so I was wondering if I can retrieve mail account information using PHP?
If not, is there another way of doing this? (I'm not too familiar with console commands)
In this answer I skip the Plesk API altogether, and I assume you either store the properties of the mailboxes in a database, hardcode it, or actually use the Plesk API to retrieve it.
Here is how I retrieve the space used by a mailbox:
function getSpaceUsedByMailBox($username,$password)
{
// open mailbox
$mailBox = imap_open('{localhost:110/pop3/novalidate-cert}INBOX',$username,$password);
// test if successful
$errors = imap_errors();
if ($errors === FALSE)
{
// get info
$info = imap_mailboxmsginfo($mailBox);
// give feedback
echo "Mailbox of $username contains ".$info->Nmsgs.
' messages and is '.$info->Size.' bytes big.';
// flush notices
imap_errors();
imap_alerts();
// close mailbox
imap_close($mailBox);
// return info
return $info;
}
// change this to proper error handling
echo 'ERROR: '.print_r($errors);
// return nothing
return NULL;
}
This is just to give you an idea. You have to adapt it to your coding style.

Debugging SMTP email failures - GSuite

I am working on an eCommerce site that sends a number of emails to the customer when they complete their order using G Suite SMTP relay service. But a large number of these emails are failing. There does not seems to be any pattern to it either - sometimes all emails will send, some times just one or two, and sometimes none.
I am getting the following error: 421, "4.7.0", Try again later, closing connection.
Looking here: https://support.google.com/a/answer/3726730?hl=en doesn't really help me debug this or figure out why some emails fail.
I am using the phpmailer class (https://sourceforge.net/projects/phpmailer/)
The issue seems to occur when the first handshake fails:
function Hello($host="") {
$this->error = null; # so no confusion is caused
if(!$this->connected()) {
$this->error = array(
"error" => "Called Hello() without being connected");
return false;
}
# if a hostname for the HELO was not specified determine
# a suitable one to send
if(empty($host)) {
# we need to determine some sort of appopiate default
# to send to the server
$host = "localhost";
}
// Send extended hello first (RFC 2821)
//If this fails then the second attempt will always fail
if(!$this->SendHello("EHLO", $host))
{
//when this fails it generates the try again later error
if(!$this->SendHello("HELO", $host))
return false;
}
return true;
}
So what is the best approach for debugging this?
The error message is pretty explicit. You call a 3rd party web service, which returns an error code which says the server you are calling is at capacity, try later. Is this a free service which allows you to upgrade to a paid plan? Usually whee you see his kind of thing.

Extract Host Name from "gethostbyaddr" string

I wish to extract the exact hostname from an ip address but what i am receiving is an entire string of the address.
I would just like to extract only the Host Name from the the string. Can any one point me in the right direction ?
Here is the snippet of the code being used:-
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$fullhost = gethostbyname(gethostbyaddr($ip));
$host = preg_replace("/^[^.]+./", "*.", $fullhost);
?>
Host: <?=$host?>
The output received from it is :-
Host: *.36.64.182.airtelbroadband.in
I would just like to display Airtel Broadband and nothing else to the user
You can try this:
$host = gethostbyaddr($_SERVER['REMOTE_ADDR']); // gets the full hostname
$hostNames = explode(".", $host); // explodes into parts divided by DOT
echo $hostNames[count($hostNames)-2]; // take what you need
// $hostNames[count($hostNames)-1]; -> in
// $hostNames[count($hostNames)-2]; -> airtelbroadband
You might also want to look into geoip.
This is a basic PHP extension that can be installed using PECL.
string geoip_isp_by_name ( string $hostname )
The geoip_isp_by_name() function will return the name of the Internet Service Provider (ISP) that an IP is assigned to.
This function is currently only available to users who have bought a commercial GeoIP ISP Edition. A warning will be issued if the proper database cannot be located.
Consider this simple example:
<?php
$subject = 'Host: *.36.64.182.airtelbroadband.in';
$pattern = '/^Host:\s+((\*|\d+)\.){4}(.+)\..+$/';
preg_match($pattern, $subject, $tokens);
var_dump($tokens[3]);
The output obviously is:
string(15) "airtelbroadband"
That is all the information you can rip from your input. If you really want to somehow show the "publicly known company names" (as opposed to the technical network names), then you need to use some form of catalog. It is very hard to somehow retrieve such information directly from the network. You could give the whois database a try. But parsing the output of that will be a really tough task...

Collect data from email message

I want to collect data from email to mysql database using php.
If some one is sent a mail to their mail account to my mail id. I want that mail information to store in my database. for further operation. It is possible in PHP because I saw this feature in one hosting support application Kayako Fusion which developed by PHP.
So plese give some information to do this task.
If you want to parse with PHP the best way is to use a 3rd party API to revive the email and then send it to your PHP script with a HTTP Post.
I'd recommend using either sendgrid.com or mailgun.com
Both of these services will parse the email and send you the information in a http POST that you can then insert into mysql. API docs for both: MailGun Incoming Parse API / SendGrid Incoming Parse API
You can use the imap functions, for example:
<?php
$imap = imap_open("{server.example.com:143}INBOX" , 'login' , 'password');
if( $imap ) {
//Check no.of.msgs
$num = imap_num_msg($imap);
//if there is a message in your inbox
if( $num >0 ) {
//read that mail recently arrived
$the_message = imap_body($imap, $num);
//Do the stuff with $the_message
}
//close the stream
imap_close($imap);
}
You'll have to setup a cronjob (scheduled task on Windows) that connects to the Exchange or POP server, retrieve's all new emails sinds the last run and insert them into the DB.
In case of a POP mail server(I think POP will be easier), there is a comment here with all functions you need right -> here. If that doesn't work, try Googling for "PHP POP wrapper" or something similar.
In case of a Microsoft Exchange server, you'd have to use a PHP Exchange wrapper, found one here for you.
Goodluck!
You can pipe your email to a php script and then extract each part of email and store it in data base.
check this example
when you get content of email you can do what ever you want

Categories