Showing posts with label attachments. Show all posts
Showing posts with label attachments. Show all posts

Thursday, November 24, 2016

Php read email & attachments from google using oauth

You can get access token & other details to perform this action:
http://pritomkumar.blogspot.com/2016/11/using-oauth-20-for-google-client-side.html

Code snippet to read email & attachments from google using oauth

<?php
session_start();
init();
if(isset($_GET["email_id"])) {
    email_details();
}
else if(isset($_GET["email_attachment"])) {
    email_attachment();
}
else {
    list_email();
}

function init() {
    $_SESSION["google_user_id"] = "11822454346345607576118";
    $_SESSION["access_token"] = "ya29.CjCgA8bf_BCrsdfsdfsdfsdf5orH3cvbMMzQY0RX8NUrbgpNhm9oXHyAAZ0WF3Jid4WwQ";

    /* Permissions to read email */
    $_SESSION["scope"] = "https://www.googleapis.com/auth/userinfo.profile"; /* User profile */
    $_SESSION["scope"] .= " https://www.googleapis.com/auth/gmail.readonly"; /* Read mail */
}

function email_attachment() {
    $id = $_GET["email_attachment"];
    $name = $_GET["name"];
    if (!file_exists("attachments")) {
        mkdir("attachments");
    }

    $apiUrl = "https://www.googleapis.com/gmail/v1/users/".$_SESSION["google_user_id"];
    $apiUrl .= "/messages/$id/attachments/".$id;
    $apiUrl .= "?access_token=".$_SESSION["access_token"];
    $remoteFile = decode_content(json_decode(make_request($apiUrl))->data);
    $file = "attachments/".md5(time()).$name;
    file_put_contents($file, $remoteFile);
    header("Location: $file");
    exit;
}

function email_details() {
    $id = $_GET["email_id"];
    $raw = "";// "format=raw&";
    $fields = "";// "fields=raw&";
    $apiUrl = "https://www.googleapis.com/gmail/v1/users/";
    $apiUrl .= $_SESSION["google_user_id"]."/messages/$id?$raw$fields";
    $apiUrl .= "access_token=".$_SESSION["access_token"];
    //echo $apiUrl; die();
    $result = json_decode(make_request($apiUrl));
    //file_put_contents("raw-email.txt", $result->raw); die();
    //echo "<pre>"; print_r($result); echo "</pre>"; die();

    $message = parse_email($result->payload->parts);
    $link = ""; $html = "";
    foreach($message as $msg) {
        if($msg["type"] == "html") {
            $html = $msg["body"];
        }
        else if($msg["type"] == "text") {
            //you can do anything with text part of email
        }
        else {
            $link .= "<a href='?email_attachment=".$msg["body"]."&name=".$msg["name"]."' target='_blank'>".$msg["name"]."</a><br/>";
        }
    }
    echo "<h3><i>Email Attachments:</i></h3>".$link."<h3><i>Email Body:</i></h3>".trim($html);
}

function parse_email($email) {
    $result = array();
    for($i = 0; $i < count($email); $i++) {
        $part = $email[$i];
        $mime = $part->mimeType;
        $name = $part->filename;
        if(strlen($name) > 0) {
            $file = array();
            $file["type"] = $mime;
            $file["name"] = $name;
            $file["body"] = $part->body->attachmentId;
            array_push($result, $file);
        }
        else if($mime === "text/plain") {
            $file = array();
            $file["type"] = "text";
            $file["name"] = "email_body_plain.html";
            $file["body"] = decode_content($part->body->data);
            array_push($result, $file);
        }
        else if($mime === "text/html") {
            $file = array();
            $file["type"] = "html";
            $file["name"] = "email_body_html.html";
            $file["body"] = decode_content($part->body->data);
            array_push($result, $file);
        }
        else if(substr($mime, 0, 9) === "multipart") {
            foreach(parse_email($part->parts) as $file) {
                array_push($result, $file);
            }
        }
    }
    return $result;
}

function decode_content($content) {
    return base64_decode(str_replace("-", "+", str_replace("_", "/", $content)));
}

function list_email() {
    //gmail api ref page: https://developers.google.com/gmail/api/v1/reference/
    //https://developers.google.com/gmail/api/v1/reference/users/messages/list
    //Searching filtering gmail over oauth2 api using php
    //https://developers.google.com/gmail/api/guides/filtering
    //https://support.google.com/mail/answer/7190?hl=en

    $search = "from:pritom@xxx.com OR from:pritomkucse@gmail.com"; //Search by from address
    $search = "subject:Fwd:"; //Words in the subject line
    $search = "label:sent OR label:starred"; //With certain labels
    $search = "has:attachment"; //Any email with attachments
    $search = "is:important"; //Important mails only
    $search = "is:read"; //For mails those are read already
    $search = "is:unread"; //For mails those are not read yet
    $search = "cc:pritomkucse@gmail.com"; //Emails has specific cc, bcc not allowed
    $search = "after:2016/11/19 AND label:inbox"; //Emails reached inbox after specific date
    $search = "before:2016/04/19 AND label:inbox"; //Emails reached inbox before specific date
    $search = "has:nouserlabels"; //Emails with no labels
    $search = "deliveredto:pritom@xxx.com"; //Emails delivered to some address
    $search = "size:10000"; //Email larger than bytes
    $search = "larger:15M"; //Emails larger than megabytes
    $search = "smaller:1M"; //Emails smaller than megabytes
    $search = "newer_than:1d"; //Emails newer than 1 day (d/m/y)
    $search = "older_than:20d"; //Emails older than 1 day (d/m/y)
    $search = "category:updates"; //Emails in specific category
    $search = "rfc822msgid:2021140448.450273.1479617087520.JavaMail.zimbra@bitmascot.com"; //Specific message by Message-ID
    $search = "!from:@gmail.com"; //Search by not from domain
    $search = "!from:pritomkucse@google.com"; //Search by not from address
    $search = ""; //No filtering

    $maxResults = 10;
    $apiUrl = "https://www.googleapis.com/gmail/v1/users/".$_SESSION["google_user_id"]."/messages?";
    $apiUrl .= "access_token=".$_SESSION["access_token"];
    $apiUrl .= "&maxResults=".$maxResults;
    if(strlen($search) > 0) {
        $apiUrl .= "&q=" . urlencode($search);
    }
    if(isset($_GET["next_page"]) && strlen($_GET["next_page"]) > 0) {
        $apiUrl .= "&pageToken=". $_GET["next_page"];
    }
    $result = json_decode(make_request($apiUrl));
    //echo "<pre>";print_r($result);echo "</pre>";die();

    if(isset($result->messages)) {
        foreach($result->messages as $m) {
            $link = "<a target='_blank' href='?email_id=".$m->id."'>View Message [[".$m->id . "]]</a><br/>";
            echo $link;
        }
    }
    else {
        echo "<pre>"; print_r($result); echo "</pre>"; die();
    }
    if(isset($result->nextPageToken)) {
        echo "<a href='?email=true&next_page=".$result->nextPageToken."'>Next_Page</a>";
    }
}

function make_request($url, $post = null, $headers = null, $returnArray = false) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, $post == null ? 0 : 1);
    if($post != null) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    if($headers != null) {
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
    curl_close($curl);
    if($http_code >= 400) {
        echo "Error executing request to Office365 api with error code=$http_code<br/><br/>\n\n";
        echo "<pre>"; print_r($response); echo "</pre>";
        die();
    }
    if($returnArray) {
        return array(
            "response" => $response,
            "header_size" => $header_size
        );
    }
    return $response;
}
?>

Wednesday, August 13, 2014

Python send plain/html email with attachment using smtp


import os
import tempfile
import mimetypes

from email.Utils import COMMASPACE, formatdate
from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)
from email.MIMEText import MIMEText
from email.MIMEBase import MIMEBase
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.MIMEAudio import MIMEAudio
from email import Encoders


SMTPserver = 'smtp.mail.yahoo.com';
sender =     'some.name@yahoo.com';
destination = ['some.name@domain.com'];

USERNAME = "some.name@yahoo.com";
PASSWORD = "some.password";

contentHtml = """\
<b>Html message</b>
<div><span style='color: red'>Span with color red</span></div>
<div><span style='color: blue'>Span with color blue</span></div>
""";

contentPlain = 'Plain message';

contentAsPlainTextFile = 'Content as plain text file.';

subject = "Sent from Python";

conn = None;
try:
    msg = MIMEMultipart()
    msg['Subject'] = subject;
    msg['From'] = sender;
    msg['To'] = COMMASPACE.join(destination);
    msg['Date'] = formatdate(localtime=True);

    #Typical values for text_subtype are plain, html, xml
    msg.attach( MIMEText(contentHtml, 'html') );
    msg.attach( MIMEText(contentPlain, 'plain') );

    directory = os.path.dirname(os.path.realpath(__file__))
    files = [];
    files.append(os.path.join(directory, 'mail.simple.py'));
    files.append(os.path.join(directory, 'royal.jpg'));
    files.append(os.path.join(directory, 'audio.rm'));
    files.append(os.path.join(directory, 'xml7.xml'));

    tempdirectory = tempfile.mkdtemp()
    tempfilelocal = os.path.join(tempdirectory, 'Custom Text As Attachment.txt');
    tempfilelocal = open(tempfilelocal, 'w+b');
    tempfilelocal.write(contentAsPlainTextFile);
    tempfilelocal.seek(0);
    tempfilelocal.close();
    files.append(tempfilelocal.name);

    for fullpath in files:
        if not os.path.isfile(fullpath):
            continue;
        ctype, encoding = mimetypes.guess_type(fullpath);
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream';
        maintype, subtype = ctype.split('/', 1);
        if maintype == 'text':
            fp = open(fullpath);
            msgpart = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'image':
            fp = open(fullpath, 'rb')
            msgpart = MIMEImage(fp.read(), _subtype=subtype)
            fp.close()
        elif maintype == 'audio':
            fp = open(fullpath, 'rb')
            msgpart = MIMEAudio(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(fullpath, 'rb')
            msgpart = MIMEBase(maintype, subtype)
            msgpart.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            Encoders.encode_base64(msgpart)
        # Set the filename parameter
        msgpart.add_header('Content-Disposition', 'attachment', filename=os.path.basename(fullpath))
        msg.attach(msgpart);

    conn = SMTP(SMTPserver);
    conn.set_debuglevel(False);
    conn.login(USERNAME, PASSWORD);
    conn.sendmail(sender, destination, msg.as_string());
    print("Mail sent.");
except Exception, exc:
    print( "Mail send failed: %s" % str(exc) );
finally:
    if conn is not None:
        conn.close()
        print("Connection closed.");

If server name and credentials are correct, you will receive email as below. In my case, it is my gmail inbox.


Sunday, July 21, 2013

Sending E-mails in php using yahoo smtp

<?php 
require 'Mail/class.phpmailer.php';

$mail = new PHPMailer; 
$mail->IsSMTP(); // Set mailer to use SMTP  
$mail->Host 'plus.smtp.mail.yahoo.com'// Specify main and backup server 
$mail->SMTPAuth   true// Enable SMTP authentication  
$mail->Username   'yourname@yahoo.com'// SMTP username  
$mail->Password   'xxxxxxxxxxxxxxxxxxxxx'// SMTP password  
$mail->SMTPSecure 'ssl'// Enable encryption, 'ssl', 'tls' etc...  
$mail->Port       465// or 587 
$mail->Timeout    60// Message sent timeout  
$mail->From       'yourname@yahoo.com'; 
$mail->FromName   'Pritom Kumar Mondal'; 
// Add a recipient 
$mail->AddAddress('yourname@gmail.com''Pritom GMAIL'); 
$mail->AddAddress('yourname@yahoo.com''Pritom YAHOO'); 
$mail->AddReplyTo('yourname@gmail.com''Reply To');

$mail->AddCC('yourname@gmail.com');
$mail->AddBCC('yourname@gmail.com'); 
$mail->WordWrap 50// Set word wrap to 50 characters

// Add attachments 
 

$mail->AddAttachment('C:\\Contact List.csv''pritom.csv'); // Optional name 
$mail->IsHTML(true); // Set email format to HTML  
$mail->Subject 'E-mail sent using yahoo smtp'; 

$mail->Body    'This is the HTML message body <b>in bold!</b>, sent using yahoo smtp';

$mail->AltBody 'This is the body in plain text for non-HTML mail clients';

if (!
$mail->Send()) {
    echo 
'Message could not be sent.';
    echo 
'Mailer Error: ' $mail->ErrorInfo;
    exit;
}
echo 
'Message has been sent';?>

Saturday, July 20, 2013

Send HTML and TEXT emails with PHP, PHPMailer, Attachments

If you are developing applications using PHP and you need to send email you can use the PHPMailer() class in PHP. Using a publicly available SMTP server to send the email is much easier than trying to setup your own email server. The following code snippet shows the various settings for the mailer. The code assumes that you have PHP 5.x version and you have class.phpmailer.php file in the include directory. Google uses ssl for the smtp connection. In order for this example to work with google smtp server, you need to enable ssl in your php.ini file by adding a line that says extension=php_openssl.dll

If you are not sure of the exact location of the php.ini file and you are using xampp, you can find the location of the php.ini file by navigating to http://localhost/xampp/phpinfo.php on your browser and look for the text "Loaded Configuration File". Once you find the file, edit it and look for the text "extension=php_openssl.dll". If the text is not found in your file, add a new line at the end of the file with the above text.
 
<?php
require 'Mail/class.phpmailer.php'; 
$mail = new PHPMailer; 
$mail->IsSMTP(); // Set mailer to use SMTP 
$mail->Host       'smtp.gmail.com'// Specify main and backup server 
$mail->SMTPAuth   true// Enable SMTP authentication 
$mail->Username   'username@gmail.com'// SMTP username 
$mail->Password   'XXXXXX'// SMTP password 
$mail->SMTPSecure 'ssl'// Enable encryption, 'ssl', 'tls' etc...
$mail->Port       465// or 587 
$mail->Timeout    60// Message sent timeout 
$mail->From       'username@gmail.com'; 
$mail->FromName   'Pritom K Mondal';

// Add a recipient
$mail->AddAddress('username@gmail.com''Pritom GMAIL'); 
$mail->AddAddress('username@yahoo.com''Pritom YAHOO');
$mail->AddAddress("username@domain.com""Pritom Domain"); 

$mail->AddReplyTo('username@gmail.com''Reply To');
$mail->AddCC('username@gmail.com'); 
$mail->AddBCC('username@gmail.com'); 
$mail->WordWrap 50// Set word wrap to 50 characters 

// Add attachments
$mail->AddAttachment('C:\\pritom.zip'); 
$mail->AddAttachment('C:\\Contact List.csv''pritom.csv'); // Optional name 

$mail->IsHTML(true); // Set email format to HTML 
$mail->Subject 'Here is the subject'; 
$mail->Body    'This is the HTML message body <b>in bold!</b>';
$mail->AltBody 'This is the body in plain text for non-HTML mail clients';

if (!
$mail->Send()) {
    echo 
'Message could not be sent.';
    echo 
'Mailer Error: ' $mail->ErrorInfo;
    exit;
}

echo 'Message has been sent'; 
?>

Download PHPMailer from here
https://github.com/Synchro/PHPMailer