Getting e-mail ID of sender while fetching mails from Gmail - php

I am fetching email from gmail where I can fetch body, name of the sender etc. I have to get the email-id of the sender, which I am not able to get. I have tried with some variables names like fromaddress after fetchting headerinfo by imap_header but didn't work.
Can I get some help regarding this ?
function connect_mail(){
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '*****#gmail.com';
$password = '*****';
$inbox = imap_open($hostname,$username,$password) or die(t('Cannot connect to Gmail: ' . imap_last_error()));
$emails = imap_search($inbox,'ALL');
$Msgcount = count($emails);
for ($x = 1; $x <= $Msgcount; $x++)
{
$overview = imap_fetch_overview($inbox, $x);
$title = $overview[0]->subject;
echo "Subject of the Mail : ".$title."</br>";
$from = $overview[0]->from;
echo "Name of the sender : ".$from."</br>";
//Now I have to get mail ID of senders & print it, but how?
}
}
I have tried my luck with several methods but got failed each time...
Thanks in Advance :)

I have done it..Hurray!
Here is the code:-
function connect_mail(){
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '*****#gmail.com';
$password = '*****';
$inbox = imap_open($hostname,$username,$password) or die(t('Cannot connect to Gmail: ' . imap_last_error()));
$emails = imap_search($inbox,'ALL');
$Msgcount = count($emails);
for ($x = 1; $x <= $Msgcount; $x++)
{
$overview = imap_fetch_overview($inbox, $x);
$title = $overview[0]->subject;
echo "Subject of the Mail : ".$title."</br>";
$from = $overview[0]->from;
echo "Name of the sender : ".$from."</br>";
$header = imap_headerinfo($inbox, $x);
$fromaddress = $header->from[0]->mailbox . "#" . $header->from[0]->host;
echo "From E-Mail Address : ".$fromaddress.;
}
}
Thanks :)

Related

How to get latest Unread email from primary tab using gmail IMAP

HI Have requirement of creating ticket if any new mail come to gmail account.
but problem with current implementation is even its a promotional email or socail email its creating a ticket.
is there is some way we can sort email based on category?
is there a way we can identify its a looped mail not new email
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'support#xyz.com';
$password = 'ywowahvxitmesssskvly';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$today = \Carbon\Carbon::now()->format('j-M-Y');
/* grab emails */
$emails = imap_search($inbox,'UNANSWERED');
dd($emails);
/* if emails are returned, cycle through each... */
if($emails) {
/* put the newest emails on top */
rsort($emails);
/* for every email... */
$emailStatus = "";
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
// $message = imap_fetchbody($inbox,$email_number,2);
// $message = ((imap_fetchbody($inbox, $email_number, 2)));
$message = quoted_printable_decode(imap_fetchbody($inbox, $email_number, 1.1));
if ($message == '') {
$message = quoted_printable_decode(imap_fetchbody($inbox, $email_number, 2));
}
/* output the email header information */
$header = imap_headerinfo ( $inbox, $email_number);
$emailStatus = $overview[0]->seen;
$emailSubject = $overview[0]->subject;
$emailFromName = $header->from[0]->personal;
$emailFromEmail = $header->from[0]->mailbox .'#'.$header->from[0]->host ;
$emailDate = $overview[0]->date;
$emailBody = base64_encode($message);
$emailMessageId = $overview[0]->message_id;
try{
if(!$emailStatus)
{
$ticket = new Ticket();
$ticket->title = $emailSubject??'';
$ticket->content = base64_encode($message)??'';
$ticket->author_name = $emailFromName??'';
$ticket->author_email = $emailFromEmail??'';
$ticket->status_id = 1;
$ticket->category_id = 1;
$ticket->priority_id = 1;
$ticket->assigned_to_group_id = 1;
$ticket->is_created_from_mailbox = 1;
$ticket->message_id = $emailMessageId;
// dd($ticket);
$ticket->save();
}
imap_setflag_full($inbox, $email_number, "\\Seen \\Flagged");
}catch(\Exception $e)
{
// dd($e->getMessage());
\Log::error("error form gamil ===" .$e->getMessage());
}
}
}
/* close the connection */
imap_close($inbox);

IMAP body displaying raw data

I'm using php imap functiona to get mail content.
Following is my code:
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = $_REQUEST['email'];
$password = $_REQUEST['pwd'];
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
$emails = imap_search($inbox,'ALL');
if($emails) {
$output = '';
rsort($emails);
$i = 0;
foreach($emails as $email_number)
{
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_qprint(imap_body($inbox, $email_number));
}
}
Displaying html data as it is in my mail body along with some raw data. How can I remove this.
--94eb2c03a0feeaad70054df6411a
Content-Type: text/plain; charset=UTF-8; format=fowed; delsp=yes
Content-Transfer-Encoding: base64
PT09IEZpbmFuY2UgLSAxIG5ldyByZXN1bHQgZm9yIFthbGliYWJhXSA9PT0NCg0KDQo8aHR0cHM6
Ly93d3cuZ29vZ2xlLmNvbS91cmw/cmN0PWomc2E9dCZ1cmw9JmN0PWdhJmNkPUNBRVlBQ29UTnpN
ek1EUTBPREE0TVRnNU9EWTJPVFl5TkRJYVptVXpOR0psT0Rnd00yTmpPREF6WXpwamIyMDZaVzQ2
VlZNJnVzZz1BRlFqQ05GMXNIbGsyejlRSXgyOGp0dmZuR1BfVWxraWZBPg0KDQoNCj09PSBOZXdz
IC0gMTAgbmV3IHJlc3VsdHMgZm9yIFthbGliYWJhXSA9PT0NCg0KQWxpYmFiYSdzIFN0cm9uZyBH
cm93dGggUmF0ZSBJcyBVbmRlcmFwcHJlY2lhdGVkDQpTZWVraW5nIEFscGhhDQpBbGliYWJhJ3Mg
aGlzdG9yaWNhbCBncm93dGggcmF0ZSBpcyBhbiBhdmVyYWdlIG9mIDUwJSBmb3IgdGhlIGxhc3Qg
Zml2ZQ0KeWVhcnMsIHdoaWNoIGlzIG5vdGhpbmcgc2hvcnQgb2Ygc3BlY3RhY3VsYXIuIE1hbmFn
ZW1lbnQgaXMgYWNjZWxlcmF0aW5nIHRoZQ0KLi4uDQo8aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS91
cmw/cmN0PWomc2E9dCZ1cmw9aHR0cHM6Ly9zZWVraW5nYWxwaGEuY29tL2FydGljbGUvNDA2NDc1
NS1hbGliYWJhcy1zdHJvbmctZ3Jvd3RoLXJhdGUtdW5kZXJhcHByZWNpYXRlZCZjdD1nYSZjZD1D
QUVZQUNvVE56TXpNRFEwT0RBNE1UZzVPRFkyT1RZeU5ESWFabVV6TkdKbE9EZ3dNMk5qT0RBell6
cGpiMjA2Wlc0NlZWTSZ1c2c9QUZRakNOSEFPUTlfSHZodHNvOVlwbnNuTk02VDdvb011Zz4NCg0K
VGhlIG5leHQgZ3JlYXQgQ0VPIGNvdWxkIGJlIGEgcm9ib3QsIEFsaWJhYmEncyBKYWNrIE1hIHNh
eXMNClVTQSBUT0RBWQ0KSmFjayBNYSwgdGhlIGZvdW5kZXIgYW5kIGNoYWlybWFuIG9mIENoaW5l
c2UgZS1jb21tZXJjZSB0aXRhbiBBbGliYWJhLA0KcHJlZGljdHMgImEgcm9ib3Qgd2lsbCBsaWtl
bHkgYmUgb24gdGhlIGNvdmVyIG9mIFRpbWUgbWFnYXppbmUgYXMgdGhlIGJlc3QNCi4uLg0KPGh0
dHBzOi8vd3d3Lmdvb2dsZS5jb20vdXJsP3JjdD1qJnNhPXQmdXJsPWh0dHBzOi8vd3d3LnVzYXRv
ZGF5LmNvbS9zdG9yeS90ZWNoL3RhbGtpbmd0ZWNoLzIwMTcvMDQvMjQvbmV4dC1ncmVhdC1jZW8t
Y291bGQtcm9ib3QtYWxpYmFiYS1qYWNrLW1hLzEwMDgzNjMzOC8mY3Q9Z2EmY2Q9Q0FFWUFTb1RO
ek16TURRME9EQTRNVGc1T0RZMk9UWXlORElhWm1Vek5
Any suggestions please.

Attachments working intermittently

I am having issues with my phpMailer script. I can email from the script, I can even send attachments from the script. However, it only works SOMETIMES and not at other times. I tried changing servers and I have the same issues so I am assuming that it is a coding issue.
when It does not work, the emails still go thorough but it is stripped from any attachments.
The attachments are definitely making it onto the server in the same location and then this script is sent an array of attachments which it then adds onto the message.
In one instance the same code and same files will send and not send! Very confusing! Usually some will send for awhile and then some will not for awhile.
Here is the code:
<?php
include('connection.php');
require_once('PHPMailer/PHPMailerAutoload.php');
class Mailer extends PHPMailer {
public function copyToFolder($folderPath) {
$message = $this->MIMEHeader . $this->MIMEBody;
$path = "INBOX" . (isset($folderPath) && !is_null($folderPath) ? ".".$folderPath : ""); // Location to save the email
$imapStream = imap_open("{mail.server.com:143/novalidate-cert}" . $path , $this->Username, $this->Password) or die(mysql_error());
imap_append($imapStream, "{mail.server.com:143/novalidate-cert}" . $path, $message)or die(mysql_error());
}
imap_close($imapStream);
}
}
$from = $_POST['from'];
$username = $from;
$grabPassword = mysql_query("SELECT * FROM `email_pw_db` WHERE `emailaddress` = '$from'");
$fetchPassword = mysql_fetch_assoc($grabPassword);
$password = $fetchPassword['password'];
$company = $_POST['to'];
$toemail = $_POST['toemail'];
$from = $username;
$namefrom = $_POST['from'];
$subject = $_POST['subject'];
$cc = trim($_POST['cc']);
$bcc = trim($_POST['bcc']);
$message = $_POST['body'];;
$attachments = $_POST['attachments'];
$mail = new Mailer();
$body = $message;
/*Create a new email*/
$mail = new Mailer();
$mail->isSMTP();
$mail->Host = 'mail.server.com';
$mail->Username = $username;
$mail->Password = $password;
$mail->From = $from;
$mail->AddReplyTo($from,$namefrom);
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent, reduces SMTP overhead
$mail->SetFrom($from, $namefrom);
$mail->AddReplyTo($from,$namefrom);
$address = $toemail;
$mail->AddAddress($address, $company);
$mail->Subject = $subject;
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($body);
if($cc!=''){
$mail->addCC($cc);
}
//CC EMAILS//
$breakOutCC = explode(',', $cc);
$countBreakOut = count($breakOutCC);
$i = 0;
while($i <$countBreakOut)
{
$mail->addCC($breakOutCC[$i]);
$i++;
}
$breakOutBCC = explode(',', $bcc);
$countBreakOutBCC = count($breakOutBCC);
$i = 0;
while($i <$countBreakOutBCC)
{
$mail->addBCC($breakOutBCC[$i]);
$i++;
}
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
$mail->AddAttachment("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
$errorMessage = $mail->ErrorInfo;
header( 'Location: email-software.php?dialog=Whoops Something Happened- '.$errorMessage ) ;
} else {
//$mail->copyToFolder(); //save email
$mail->copyToFolder("Sent"); // Will save into Sent folder
$attachments = $_POST['attachments'];
$breakoutAttachments = explode(',', $attachments);
$countAttachments = count($breakoutAttachments);
$i = 0;
while($i <$countAttachments)
{
unlink("attachments/email_attachments/".$breakoutAttachments[$i]);
$i++;
}
header( 'Location: email-software.php?dialog=email sent' ) ;
}
?>

PHPMailer - Repeating variables

I have a HTML form that is being processed by a php page. I have had it working exactly as I need using mail() but am running into issues with the email part. Sending an email out is very inconsistent which is not acceptable. I understand that mail() only takes care of a small part of the process and the mail servers take care of the heavy lifting.
I am trying out PHPMailer as an alternative. I have it up and running and am able to get mail to go out but some of the functionality is not there.
In my form you can add multiple 'projects' to a single submission. The php is supposed to loop over those projects and create a section for each in the email. Again, this is working with mail() but doesn't always send.
The code I am trying to implement is below. It will send an email but will not loop over the form fields if there are more than one. It will only see the last one entered.
<?php
require 'PHPMailerAutoload.php';
date_default_timezone_set('America/New_York');
$today = date("F j - Y - g:i a");
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'mail.example.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'mail#example.com'; // SMTP username
$mail->Password = 'password'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'mail#example.com';
$mail->FromName = 'From name';
$mail->addAddress('mail#example.com', 'personName'); // Add a recipient
//$mail->addAddress('mail#anotherexample.com'); // Name is optional
$mail->addReplyTo('mail#example.com', 'replyTO');
//$mail->addCC('cc#example.com');
//$mail->addBCC('bcc#example.com');
$mail->WordWrap = 500; // Set word wrap to 50 characters
//$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
//$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->isHTML(true); // Set email format to HTML
//VARIABLES FROM FORM FIELDS
$contractor = $_POST['ct'];
$noactive = $_POST['noconactivity'];
$hours = $_POST['hours'];
$project = $_POST['prjx'];
$city = $_POST['cx'];
$street = $_POST['street'];
$from = $_POST['from'];
$to = $_POST['to'];
$crewxtown = $_POST['cxtown'];
$construction = $_POST['construction'];
$mpt = $_POST['mpt'];
$direction = $_POST['direction'];
$police = $_POST['police'];
$optcomments = $_POST['optcomments'];
$submissionemail = $_POST['submissionemail'];
$mail_cm = $_POST['cm'];
$mail_pm = $_POST['pm'];
$intersection = $_POST['intersection'];
$parking = $_POST['parking'];
$count = count($street)-1;
$data = array();
//REPETITIVE VARIABLES
for( $i = 0; $i <= $count; $i++ )
{
$hours0 = $hours[$i];
$street0 = $street[$i];
$from0 = $from[$i];
$to0 = $to[$i];
$crewxtown0 = $crewxtown[$i];
$construction0 = $construction[$i];
$mpt0 = $mpt[$i];
$direction0 = $direction[$i];
$police0 = $police[$i];
$optcomments0 = $optcomments[$i];
$parking0 = $parking[$i];
$intersection0 = $intersection[$i];
$data[] = "$today, $noactive, $contractor, $hours0, $project, $city, $street0, $from0, $to0, $intersection0, $construction0, $mpt0, $crewxtown0, $direction0, $police0, $parking0, $optcomments0, $submissionemail, $mail_cm, $mail_pm\n";
$mail->Subject = $project;
$mail->Body = 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
}
// WRITING DATA TO CSV TABLE
if(!empty($data)) {
$data = implode('', $data);
$fh = fopen("dailyupdatedata.csv", "a");
fwrite($fh, $data);
fclose($fh);
}
//SUCCESS & FAILURE MESSAGE ON PHP PAGE
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message has been sent';
}
Here is the mail() code that works but does not consistently send.
<?php
date_default_timezone_set('America/New_York');
$contractor = $_POST['ct'];
$noactive = $_POST['noconactivity'];
$hours = $_POST['hours'];
$project = $_POST['prjx'];
$city = $_POST['cx'];
$street = $_POST['street'];
$from = $_POST['from'];
$to = $_POST['to'];
$crewxtown = $_POST['cxtown'];
$construction = $_POST['construction'];
$mpt = $_POST['mpt'];
$direction = $_POST['direction'];
$police = $_POST['police'];
$optcomments = $_POST['optcomments'];
$submissionemail = $_POST['submissionemail'];
$mail_cm = $_POST['cm'];
$mail_pm = $_POST['pm'];
$intersection = $_POST['intersection'];
$parking = $_POST['parking'];
$count = count($street)-1;
$today = date("F j - Y - g:i a");//
$message = '<html><body>';
$message .= "Please see the info blah blah<br><strong>Date:</strong> $today<br><strong>Submission by:</strong> $submissionemail<br><br>"; // Beginning message content
$data = array();
for( $i = 0; $i <= $count; $i++ )
{
$hours0 = $hours[$i];
$street0 = $street[$i];
$from0 = $from[$i];
$to0 = $to[$i];
$crewxtown0 = $crewxtown[$i];
$construction0 = $construction[$i];
$mpt0 = $mpt[$i];
$direction0 = $direction[$i];
$police0 = $police[$i];
$optcomments0 = $optcomments[$i];
$parking0 = $parking[$i];
$intersection0 = $intersection[$i];
$data[] = "$today, $noactive, $contractor, $hours0, $project, $city, $street0, $from0, $to0, $intersection0, $construction0, $mpt0, $crewxtown0, $direction0, $police0, $parking0, $optcomments0, $submissionemail, $mail_cm, $mail_pm\n";
$message .= "<strong>Project:</strong> $project<br><strong>Active / Not Active:</strong> $noactive<br><strong>Contractor:</strong> $contractor<br><strong>Town:</strong> $city<br><strong>Hours:</strong> $hours0<br><strong>Street:</strong> $street0<br><strong>From:</strong> $from0<br><strong>To:</strong> $to0<br><strong>Intersection:</strong> $intersection0<br><strong>Construction Activity:</strong> $construction0<br><strong>MPT:</strong> $mpt0<br><strong>Crew Town:</strong> $crewxtown0<br><strong>Closure Direction:</strong> $direction0<br><strong>Police & Flaggers:</strong> $police0<br><strong>Parking Restrictions:</strong> $parking0<br><strong>Optional Comments:</strong> $optcomments0<br><br> -- <br><br>"; //Data for message
}
$message .= '</body></html>';
if(!empty($data)) {
$data = implode('', $data);
$fromemail = "email#email.com"; // email#email.com
$subject = $project;
//$headers = "From:" . $fromemail;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: "."Team Traffic "." <email#email.com>" . "\r\n";
mail($submissionemail,$subject,$message,$headers); // Submission Email
mail($mail_cm,$subject,$message,$headers); // C Manager Email
mail($mail_pm,$subject,$message,$headers); // P Manager Email
mail("email#email",$subject,$message,$headers);
//mail($trafficemail,$subject,$message,$headers); // Traffic
$fh = fopen("dailyupdatedata.csv", "a");
fwrite($fh, $data);
fclose($fh);
}
?>
Am I missing a step here? Does PHPMailer not work with looping over variables?
Thank you,
Eric
$mail->Body = 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;
You are doing that in a loop, that means your code is overwriting the email body on every iteration and only the last one will stay. And then you exit the loop and send the email.
You should be appending those values to the body instead of overwriting the value.
$mail->Body.="New content for new project";
^
I think $mail->Subject = $project; should be out of the loop.
As for body I think you forgot adding a dot(.=) to accumulate the message.
$mail->Body .= 'Message content header stuff.<br><br><br><b>Street: </b> ' . $street0;

gmail not responding while connecting through imap?

I wrote a simple 3 line code for connecting to gmail through imap-php.
i am using 000webhost for running it.
but when i try to open it, it keeps on loading and after some times shows "Problem loading page" or "No data recieved", as if gmail servers are not responding!!
Any suggestions whats the problem?
$hostname = "{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}Inbox";
$username = 'abc#gmail.com';
$password = "abc123";
$inbox = imap_open($hostname,$username,$password)or die('Cannot connect to Gmail: ' . imap_last_error());
$server_name = "imap.gmail.com";
$account_name = "email#mydomain.com";
$account_pwd = "my_account_password";
$inbox = imap_open("{".$server_name.":993/imap/ssl/novalidate-cert}INBOX",
$account_name, $account_pwd) OR error_imap_mail("Unable To Open Imap
Connection","Imap Failure",imap_errors());
function error_imap_mail($subject,$messagetext,$errors) {
global $report_email;
$mailfrom = "support#mydomain.com";
$mailsubject = "$subject";
$mailbody = "$messagetext\n\n";
if (count($errors) >0) {
if (substr($errors[0],0,8) <> "[IN-USE]") {
array_reverse($errors);
foreach ($errors as $key=>$value) {
$mailbody .= "\nErr No.".$key." Error:".$value;
}
foreach ($report_email as $value) {
mail($value, $mailsubject, $mailbody, "From: $mailfrom");
}
}#if (substr($err_array[0],0,8) <> "[IN-USE]") {
}#if (count($errors) >0) {
exit;
}
Get your script to send you the errors if it fails to connect.
Have you turned IMAP on in the account setting in Gmail?
Try this:
$hostname = "{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX";
$username = 'abc#gmail.com';
$password = "abc123";
$inbox = imap_open($hostname,$username,$password)or die('Cannot connect to Gmail: ' . imap_errors());
Also make sure you enable IMAP for you account via GMail settings.

Categories