accessing my gmail inbox via php code - php

how i can access my gmail account through my php code? I need to get the subject and the from address to from my gmail account.And then i need to mark the accessed as read on gmail
Should i use gmail pop3 clint?is that any framework that i can use for accessing gmail pop3
server.

I would just use the PHP imap functions and do something like this:
<?php
$mailbox = imap_open("{imap.googlemail.com:993/ssl}INBOX", "USERNAME#googlemail.com", "PASSWORD");
$mail = imap_search($mailbox, "ALL");
$mail_headers = imap_headerinfo($mailbox, $mail[0]);
$subject = $mail_headers->subject;
$from = $mail_headers->fromaddress;
imap_setflag_full($mailbox, $mail[0], "\\Seen \\Flagged");
imap_close($mailbox);
?>
This connects to imap.googlemail.com (googlemail's imap server), sets $subject to the subject of the first message and $from to the from address of the first message. Then, it marks this message as read. (It's untested, but it should work :S)

This works for me.
<?php
$yourEmail = "you#gmail.com";
$yourEmailPassword = "your password";
$mailbox = imap_open("{imap.gmail.com:993/ssl}INBOX", $yourEmail, $yourEmailPassword);
$mail = imap_search($mailbox, "ALL");
$mail_headers = imap_headerinfo($mailbox, $mail[0]);
$subject = $mail_headers->subject;
$from = $mail_headers->fromaddress;
imap_setflag_full($mailbox, $mail[0], "\\Seen \\Flagged");
imap_close($mailbox);
?>

You can use IMAP from PHP.
<?php
$mbox = imap_open("{imap.example.org:143}", "username", "password")
or die("can't connect: " . imap_last_error());
$status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged");
echo gettype($status) . "\n";
echo $status . "\n";
imap_close($mbox);
?>

Another nice IMAP example is available at http://davidwalsh.name/gmail-php-imap

Zend Framework has the Zend_Mail API for reading mail as well. It makes it easy to switch protocols if need be (POP3, IMAP, Mbox, and Maildir). Only the IMAP and Maildir storage classes support setting flags at this time.
http://framework.zend.com/manual/en/zend.mail.read.html
Read messages example from the Zend Framework docs:
$mail = new Zend_Mail_Storage_Pop3(array('host' => 'localhost',
'user' => 'test',
'password' => 'test'));
echo $mail->countMessages() . " messages found\n";
foreach ($mail as $message) {
echo "Mail from '{$message->from}': {$message->subject}\n";
}

Related

How to send mail in WampServer using hMailServer

I have mail function in php which looks like:
<?php
$admin_email = "admin#gmail.com";
$email ="myemail#gmail.com";
$subject = "hellow ord";
$comment = "cmt";
try{
$th=mail($admin_email, $subject, $comment, "From:" . $email);
if($th)
echo "gg";
else
echo "error_message";
}
catch(Exception $e)
{
echo $e->message();
}
?>
I have Wamp server to run it. I have configured hMailServer by seeing a post on Stack Overflow but when I run the above code I get:
Warning: mail(): SMTP server response: 530 SMTP authentication is required...
Do I need to set up anything before using mail function?
The PHP mail() function doesn't support smtp authentication, which generally results in an error when connecting to public servers like the one you are trying to connect to. With hmailserver installed, you still need to use a library like PHPMailer which you can autheticate with.
Follow the steps here to setup phpmailer with gmail:
http://blog.techwheels.net/tag/wamp-server-and-phpmailer-and-gmail/
I've successfully sent email using gmail on (wamp/hmailserver/phpmailer).
<?php
require_once ("class.phpmailer.php");
$sendphpmail = new PHPMailer();
$sendphpmail->IsSMTP();
$sendphpmail->SMTPAuth = true;
$sendphpmail->SMTPSecure = "ssl";
$sendphpmail->Host = "smtp.gmail.com";
$sendphpmail->Port = 465;
$sendphpmail->Username = "your#gmail.com";
$sendphpmail->Password = "gmail_password";
$sendphpmail->SetFrom('your#gmail.com','blahblah');
$sendphpmail->FromName = "From";
$sendphpmail->AddAddress("recipient#gmail.com"); //don't send to yourself.
$sendphpmail->Subject = "Hello!";
$sendphpmail->Body = "<H3>Check out www.google.com</H3>";
$sendphpmail->IsHTML (true);
if (!$sendphpmail->Send())
{
echo "Error: $sendphpmail->ErrorInfo";
}
else
{
echo "Message Sent!";
}
?>
Hope this helps others as well. Took me a few hours of googling and compiling answers from places while facing this issue.

Sending email via PHP error

im a php beginner, and I am building a website, and website is supposed to let people send me email. the thing is i never knew anything about sending emails through php. I looked it up online and tried using the codes i found. The thing is my program says it sent the email but i never happen to get the email. I thought maybe it is because I am using apache server to test my php, and maybe it is gona work when I upload it to a real server??(yes this was a question)
Just in case, this is my code, and it is the all php code in my website, also form works fine, there is nothing wrong with it.
<?php
if (isset($_POST['name'])) {
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = "From: " . $_POST['name'] . ", " . $_POST['email'] . "\n Message: " . $_POST['message'];
try {
mail("serdarufuk95#gmail.com", $subject, $message, " ");
unset($_POST['name']);
header("Location: success.php");
}
catch (PDOException $e)
{
include 'index.html';
exit();
}
exit();
}
include 'contact2.php';
?>
is there a problem with the code? or do i have to call something from a library or anything or am i missing a code! HELP ME MAKE THIS WORK! when i execute it, it takes me to success.php, so i assumed nothing is wrong with my code, but you guys know better!
It might not work after uploading to a real server if the server's mail configuration has not been set yet. So I suggest you to use a better and simpler version in order to send mails through PHP: PHPMailer
require_once("class.phpmailer.php");
$mail = new PHPMailer();
$mail->AddAddress("mail#domain.com","Display name");
$mail->Subject= "Mail subject";
$mail->Body= "Mail content";
$mail->IsSMTP();
$mail->Host = "mail.domain.com";
$mail->SMTPAuth = true;
$mail->Username = "formmail#domain.com";
$mail->Password = "123456";
$mail->IsHTML(true); //true if you want to send html content. false for plain text message
$mail->From = $_POST['Email'];
$mail->FromName = $_POST['Name'];
$mail->Send();
You may download the class clicking here

Sending an email verification after registering

I want, that users who register on my site, have to activate their account first, before using it. The problem is, that I don't get any email to my email test account.
Before I start posting a code, could the problem be, that I'm working currently on a local machine with xampp?
Otherwise, here is the code snippet
$random = substr(number_format(time() * rand(),0,'',''),0,10);
$insertMailVerify = $this->db->prepare("INSERT INTO mailverify (mailAddress, token, datetime) VALUES (:mailAddress, :token, :date)");
$insertMailVerify->execute(array(':mailAddress'=>$emailAddress,
':token'=>$random,
':date'=>$date));
$to = $emailAddress;
$subject = "Activating your Account";
$body = "Hi, in order to activate your account please visit http://localhost/FinalYear/activation.php?email=".$emailAddress." and fill in the verification code $random";
if(mail($to, $subject, $body))
{
echo ("<p>Message success</p>");
}
else {
echo ("<p>Message fail</p>");
}
Just in case you wonder where i take $emailAddress from: This is just a code snippet, i already let the software echo the email address, and it's correct. It even goes in the "Message success" if case, but I still can't get any email. What could be the problem?
After submit the form you can use a code or link and send it to the user email id
$message = "Your Activation Code is ".$code."";
$to=$email;
$subject="Activation Code For Talkerscode.com";
$from = 'your email';
$body='Your Activation Code is '.$code.' Please Click On This link Verify.php?id='.$db_id.'&code='.$code.'to activate your account.';
$headers = "From:".$from;
mail($to,$subject,$body,$headers);
echo "An Activation Code Is Sent To You Check You Emails";
Code from TalkersCode.com for complete tutorial visit http://talkerscode.com/webtricks/account-verification-system-through-email-using-php.php
in local host i think the best way is using phpmailer and gmail account
here the tutorial : http://www.web-development-blog.com/archives/send-e-mail-messages-via-smtp-with-phpmailer-and-gmail/
It seems your mail server SMTP is not configured correctly....
check the port and IP of SMTP server address.
Try to change you PHP.ini file like this and tell me if it works.
[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = smtp.gmail.com
; http://php.net/smtp-port
smtp_port = 465 //if 465 is not working then try 25
If this is not working then there are a lot of tutorials of how to achieve what you are trying to do.
Here is one link: Send email from localhost
Had the same problem, but on linux.
1) Assuming your mail() function is working properly: the problem could be, that email is coming into spam-box (because these localhost mail systems are often marked as spambots, so email services are protecting emails from unverified host).
2) If mail() is not working, its not configured properly, if you follow some tutorial and configure it, which needs like 5 minutes, you will realise why not to use it:)
The best way for you is to use some free or paid smtp service. Very easy, quick and your emails wont be marked as spam. And install PEAR library to send email. Here is an example.
$from = 'from#domain.com';
$to = 'to#domain.com';
$subject = 'subject';
$body = 'Hello!';
$host = 'smtpserver.com';
$port = '25';
$username = 'yourlogin';
$password = 'yourpass';
$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if(PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
To your verification code: instead of telling user to write down the verification code, better generate him the link, that he clicks his account gets activated. Something like
http://localhost/FinalYear/activation.php?email=some#email.com&token=79054025255fb1a26e4bc422aef54eb4
on registration page: generate the activation token like md5($email . '_sometext');
on activation page if(md5($_GET['email'] . '_sometext') == $_GET['token']) { activate.. }
please note, that it is just an example, there are 10 ways how it could be done :)

Mail not sent in php pear mail package

I am trying to use PEAR Mail to send from my gmail address using below code,
<?php
include("Mail.php");
echo "This test mail for authentication";
try{
$from_name = "Test";
$to_name = "from name";
$subject = "hai";
$mailmsg = "Happy morning";
$From = "From: ".$from_name." <frommail#gmail.com>";
$To = "To: ".$to_name." <tomail#gmail.com>";
$recipients = "tomail#gmail.com";
$headers["From"] = $From;
$headers["To"] = $To;
$headers["Subject"] = $subject;
$headers["Reply-To"] = "gunarsekar#gmail.com";
$headers["Content-Type"] = "text/plain";
$smtpinfo["host"] = "smtp.gmail.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "mymail#gmail.com";
$smtpinfo["password"] = "mypassword";
//$smtpinfo["debug"]=True;
$mail_object =& Mail::factory("smtp", $smtpinfo);
$mail_object->send($recipients, $headers, $mailmsg);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo "<br>Fin";
?>
this code not return any error or warning , it simply shows "Message successfully sent!"
but, mail not receiver to mail the address.
can any one please tell what problem in mycode or what actually happening.,
The first thing I see is that you have a mistake: Your check checks against an variable called $mail, but everything else refers to $mail_object. If that's in your actual code, then I'm guessing that might be part of it.
Some basic checks:
Did you check to make sure that you have POP or IMAP enabled in Gmail?
Have you set up this account with the same username and password on a normal machine, to ensure you can send and receive email outside of PHP?
Verify that you can even talk to the GMail server (that it isn't blocked for some reason) by pinging smtp.gmail.com or using telnet to open a connection to port 25: telnet smtp.gmail.com 25
Read over the Gmail help for sending email.
Beyond that, it looks like GMail requires TLS or SSL, which means you have to use port 587 or port 465. I don't know if that package can handle encrypted connections, though. (Even on port 25, GMail requires SSL encryption.) That may preclude this from working at all.

Using Gmail SMTP to send email with PHP

I have a problem I have been working on for about a week and can't find an answer. As a preface to this all, I have searched the internet for all sorts of things. There are a lot of answers for this problem, but none seem to be helping me.
I am somewhat new to PHP and a lot of the stuff I am asking for (been using it over the past few months). Let me get to the base of the problem:
I am on a school network with my own server set up in my dorm room. I am creating a website where I need to verify a user's email, but the basic PHP mail() function does not work. I have been told that I will need to use SMTP. So I decided the easiest and cheapest way was with Gmail SMTP. I created an account on Gmail called verify.impressions#gmail.com for this reason. Here is the code.
echo "starting mail sending";
require_once("pear/share/pear/Mail.php");
echo "1";
$from = "PersonA `<someone#gmail.com`>"; $to = "`<someoneElse#email.com`>"; $subject = "Activate your account"; $body = "Hey";
$host = "ssl://smtp.gmail.com"; $port = "465"; //also tried 587 $username = "someone#gmail.com"; $password = "password";
echo "2";
$headers = array ('From' => $from, 'To' => $to, 'Subject' => $subject);
echo "3";
$mailer_params['host'] = $host; $mailer_params['port'] = $port; $mailer_params['auth'] = true; $mailer_params['username'] = $username; $mailer_params['password'] = $password;
$smtp = Mail::factory('smtp', $mailer_params);
echo "4";
error_reporting(E_ALL);
echo "5";
if (PEAR::isError($smtp)) { die("Error : " . $smtp->getMessage()); }
echo "6";
$mail = $smtp->send($to, $headers, $body) or die("Something bad happened");
echo "7";
if (PEAR::isError($mail)) {echo($mail->getMessage();} else {echo(Message successfully sent!);}
echo "mail sent hopefully.";
So basically the code just stops at the line:
$mail = $smtp->send($to, %headers, $);
I have tried printing errors, but I just have no idea what to do now. Any tips and help is appreciated. Thanks!!
Use this class: http://www.phpclasses.org/package/14-PHP-Sends-e-mail-messages-via-SMTP-protocol.html
The sample code I use:
require("smtp/smtp.php");
require("sasl/sasl.php");
$from = 'youraddress#gmail.com';
$to = 'some#email.com';
$smtp=new smtp_class;
$smtp->host_name="smtp.gmail.com";
$smtp->host_port='465';
$smtp->user='youraddress#gmail.com';
$smtp->password='XXXXXXXXX';
$smtp->ssl=1;
$smtp->debug=1; //0 here in production
$smtp->html_debug=1; //same
$smtp->SendMessage($from,array($to),array(
"From: $from",
"To: $to",
"Subject: Testing Manuel Lemos' SMTP class",
"Date: ".strftime("%a, %d %b %Y %H:%M:%S %Z")
),
"Hello $to,\n\nIt is just to let you know that your SMTP class is working just fine.\n\nBye.\n"));
If you are you using Linux I recommend setting up postfix on your local machine and they asking that to relay the email forwards via an external SMTP service, in your case Gmail.
http://bookmarks.honewatson.com/2008/04/20/postfix-gmail-smtp-relay/
The reason is that your PHP script can timeout incase there's a delay contact Gmail. So you would use Postfix to queue the email on the local server, let the PHP script execution die and trust Postfix to send the email via Gmail.
If you are using Windows, I am sure you can find an equivalent SMTP relay application (should be built as a rough guess).
Many public networks block connections on the SMTP port to remote machines to stop spammers inside their network.
You have two choices:
Find a smtp server that uses a different port than 25
Use the official SMTP server of your school's network. There is always one since people need to send mails out.
I always use this to send mails using gmail as SMTP server.
Very Simple to configure

Categories