Search code examples
symfonyimap

Correct way to retrieve mails by IMAP in symfony2


I have to develop simple mail client in symfony2 using IMAP. Im wondering what is best way to retrieve messages from server (lets take a gmail as example)?

I did something like this:

public function indexAction($name)
{
    $user = 'adress@gmail.com';
    $password = 'password';
    $mailbox = "{imap.gmail.com:993/imap/ssl}INBOX";
    $mbx = imap_open($mailbox , $user , $password);
    $ck = imap_check($mbx);
    $mails = imap_fetch_overview($mbx,"1:5");
    return $this->render('HtstMailBundle:Mail:index.html.twig',array('name'=>$name,'mail'=>$mails));
}

is this right way, or not? It works, but is it compatible with symfony "standards"?


Solution

  • This has nothing to do with symfony "standards". But you can make your code more OOP if you move all login to a service class and use symfony DepencyInjection to create and get your service:

    public function indexAction($name)
    {
        $user = 'adress@gmail.com';
        $password = 'password';
        $mailbox = "{imap.gmail.com:993/imap/ssl}INBOX";
        $mails = $this->get("mail.checker")->receive($user, $password, $mailbox);
        return $this->render('HtstMailBundle:Mail:index.html.twig',array('name'=>$name,'mail'=>$mails));
    }
    

    Class declaration:

    class MailChecker
    {
        public function receive($user, $password, $mailbox)
        {
            ...imap_check()...
        }
    }
    

    service declartion:

    services:
        mail.checker:
            class: Project\YourBundle\Service\MailChecker