This topic is locked

Read and Send email in GMAIL account

10/6/2020 6:14:16 AM
PHPRunner Tips and Tricks
fhumanes author

PostReader


I have done this example to handle emails, reading them from a GMAIL account and sending new emails through the same account.
I have oriented the example to a support or incident manager to users of a system where their means of reporting problems and receiving a reply is email. As I always indicate, this is not an application, but an example that you must customize for your requirements.
Objective
The objective that I have set is to provide simple and efficient code so that from PHPRunner we can read the messages that arrive at a Gmail email account and send emails to the people who previously made their query.
For those who want to receive and send emails from PHPRunner, this will be an example that facilitates these functions.
Example functionality


DEMO: https://fhumanes.com/postreader/
User: admin

Password: admin.
The email account that you use and to which you can send test messages is: fhumanes.pruebas@gmail.com
The example has a “Config” option that allows configuring the example in the characteristics of the mail accounts, the destination mailbox of the messages, the directory of the files, etc.


The important option is "email", which is what is displayed. I have used some yellow balls to mark the most relevant points that I am going to describe.
(1) .- With this orange button, the application reviews and retrieves the messages from fhumanes.pruebas@gmail.com. For the example, it runs directly from the button, but for a productive system it should be included in the CRON and run every 5 minutes at most. The necessary changes are simple and if you have questions or problems, tell me and I will do them for you.
(2) .- As an example, it has been given that the message may be related to:

  • Contacts .- They would be the general data of all users of the system. The relationship is by email.
  • Other messages .- Other messages that are in the system with this same email account.
  • Responses.- From this link we create and consult the procedures and response that we have made on this message. For each Reply record, the example sends an email to the original account of the message.


(3) .- State in which the message is found. This status is updated with the responses that are made.
Technical solution
As I always do, I try to find a PHP library that does the functionality I require, in this case I have used:
phpmailer 6.1 .- For sending messages. https://github.com/PHPMailer/PHPMailer

php-imap 4.1, by Sergey Barbushin.- For reading messages and moving them to the archive mailbox. https://github.com/barbushin/php-imap/
I show you the most important code that the example has:
read_mail.php





<?php

/**

* Example: Get and parse all unseen emails with saving their attachments one by one.

*

* @author Sebastian Krätzig <info@ts3-tools.info>

*/



global $conn;



require_once __DIR__.'/../php-imap_4.1.0/autoload.php';

use PhpImap\Exceptions\ConnectionException;

use PhpImap\Mailbox;

// Load variables of Config

$serverMail = $_SESSION['config'][array_search('GMAIL_server', array_column($_SESSION['config'], 'name'))][value];

$login = $_SESSION['config'][array_search('GMAIL_Username', array_column($_SESSION['config'], 'name'))][value];

$password = $_SESSION['config'][array_search('GMAIL_Password', array_column($_SESSION['config'], 'name'))][value];

$buzonArchivo = $_SESSION['config'][array_search('ARCHIVE_Mailbox', array_column($_SESSION['config'], 'name'))][value];

$directoryAttachments = $_SESSION['config'][array_search('FOLDER_FILES', array_column($_SESSION['config'], 'name'))][value];



$dateEmail = '' ;

$from_name = '';

$from_email = '';

$to = '';

$subject = '';

$message = '';



$message_id = '';

$num_message = 0;



$mailbox = new Mailbox(

$serverMail, // IMAP server and mailbox folder

$login, // Username for the before configured mailbox

$password // Password for the before configured username

);

try {

$mail_ids = $mailbox->searchMailbox('UNSEEN');

} catch (ConnectionException $ex) {

die('IMAP connection failed: '.$ex->getMessage());

} catch (Exception $ex) {

die('An error occured: '.$ex->getMessage());

}



foreach ($mail_ids as $mail_id) {

$email = $mailbox->getMail(

$mail_id, // ID of the email, you want to get

true // Do NOT mark emails as seen (optional)

);

$from_name = (isset($email->fromName) ? $email->fromName : $email->fromAddress);

$from_email = $email->fromAddress;

$to = $email->toString;

$subject = $email->subject;

$message_id = $email->messageId;

$dateEmail = date("Y-m-d H:i:s", strtotime($email->date));

// Save attachments one by one

if (!$mailbox->getAttachmentsIgnore()) {

$attachments = $email->getAttachments();



$num_attachment = 0;

$fileAttachment = [];

foreach ($attachments as $attachment) {

$usrName = $attachment->name;

$extension = $attachment->subtype;

$name = $directoryAttachments.'/'.time().'_'.str_replace(' ', '_', $usrName);

$pathFile = substr(__DIR__, 0, -4).'/'.$name;

$attachment->setFilePath($pathFile);

if ($attachment->saveToDisk()) {

// echo "OK, saved!\n";

} else {

// echo "ERROR, could not save!\n";

}

$size = filesize($pathFile);



// Mime Type

$sql = "SELECT MimeType FROM mime_type where Extension = lower('$extension')";

$rs = $conn->query($sql);

if ($data = $rs->fetch_assoc()) {

$type = $data[MimeType];

} else {

$type = 'application/octet-stream';

};



$fileAttachment[$num_attachment][name]= $name;

$fileAttachment[$num_attachment][usrName]= $usrName;

$fileAttachment[$num_attachment][size]= $size;

$fileAttachment[$num_attachment][type]= $type;

$fileAttachment[$num_attachment][searchStr] = $usrName.',!:sStrEnd';



$num_attachment = $num_attachment + 1;

}

}

if ($email->textHtml) {

$message = $email->textHtml;

} else {

$message = $email->textPlain;

}

if (!empty($email->autoSubmitted)) {

// Mark email as "read" / "seen"

$mailbox->markMailAsRead($mail_id);

}

if (!empty($email_content->precedence)) {

// Mark email as "read" / "seen"

$mailbox->markMailAsRead($mail_id);

}



$mailbox->moveMail($mail_id,$buzonArchivo);



$sql = "insert INTO email (FromEmail, FromName, toEmail, Date, Subject, Message, Attachment) values

(?,?,?,?,?,?,?)";

$rs = $conn->prepare($sql);

$rs->bind_param('sssssss', $from_email, $from_name, $to, $dateEmail, $subject, $message, $attachment);

$attachment = my_json_encode($fileAttachment);

// $subject = addslashes($conn->real_escape_string($subject));

// $message = addslashes($conn->real_escape_string($message));

$rs->execute();

$num_message = $num_message + 1;

}

$mailbox->disconnect();


send_mail.php





<?php

// For send of email response

// field of Config

$GMAIL_Username = $_SESSION['config'][array_search('GMAIL_Username', array_column($_SESSION['config'], 'name'))][value];

$GMAIL_Password = $_SESSION['config'][array_search('GMAIL_Password', array_column($_SESSION['config'], 'name'))][value];

$GMAIL_setFrom_email = $_SESSION['config'][array_search('GMAIL_setFrom_email', array_column($_SESSION['config'], 'name'))][value];$GMAIL_Username = $_SESSION['config'][array_search('GMAIL_Username', array_column($_SESSION['config'], 'name'))][value];

$GMAIL_setFrom_name = $_SESSION['config'][array_search('GMAIL_setFrom_name', array_column($_SESSION['config'], 'name'))][value];

//Import PHPMailer classes into the global namespace

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\SMTP;

require __DIR__.'/../phpmailer_6.1/autoload.php';

//Create a new PHPMailer instance

$mail = new PHPMailer;

// Activo condificacción utf-8

$mail->CharSet = 'UTF-8';

//Tell PHPMailer to use SMTP

$mail->isSMTP();

//Enable SMTP debugging

// SMTP::DEBUG_OFF = off (for production use)

// SMTP::DEBUG_CLIENT = client messages

// SMTP::DEBUG_SERVER = client and server messages

$mail->SMTPDebug = SMTP::DEBUG_OFF;

//Set the hostname of the mail server

$mail->Host = 'smtp.gmail.com';

// use

// $mail->Host = gethostbyname('smtp.gmail.com');

// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission

$mail->Port = 587;

//Set the encryption mechanism to use - STARTTLS or SMTPS

$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;

//Whether to use SMTP authentication

$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail

$mail->Username = $GMAIL_Username;

//Password to use for SMTP authentication

$mail->Password = $GMAIL_Password;

//Set who the message is to be sent from

$mail->setFrom($GMAIL_setFrom_email,$GMAIL_setFrom_name);

//Set an alternative reply-to address

// $mail->addReplyTo('fernandohumanes@gmail.com', 'First Last');

//Set the subject line

$mail->Subject = $values['Subject'];

//Read an HTML message body from an external file, convert referenced images to embedded,

//convert HTML into a basic plain-text alternative body

$message = $values['Message'];

// $mail->msgHTML($message);

/*

// Attachments

$filesArray = my_json_decode($masterData['attachments']);

foreach ($filesArray as $File) {

$mail->addAttachment(__DIR__."/../".$File["name"],$File["usrName"],'base64', $File["type"]);

}

*/

$mail->msgHTML($message);

// $mail->AltBody = $mail->html2text($message0); // Text plain alternative

$mail->addAddress($values['toEmail'], $values['toName']);

$status = $mail->send();
?>


As always, for any questions or queries, write to my email [email="fernandohumanes@gmail.com"]fernandohumanes@gmail.com[/email]
I leave the project on my portal, so that you can execute it on your computers.