Showing posts with label send mail. Show all posts
Showing posts with label send mail. Show all posts

Monday, December 19, 2016

Java Send Email Using Office 365 OAuth Connection

Download source code from here

To get oauth access token & other information used in this code snippet visit:
http://pritomkumar.blogspot.com/2016/11/write-php-app-to-get-outlook-office-365.html



package com.pkm.office_oauth;

import com.google.gson.Gson;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by pritom on 18/12/2016.
 */
public class JavaSendMailUsingOffice365OAuth {
    private static final String OFFICE_ACCESS_TOKEN = "xxxxx";
    private static String mailUUID = "";

    /**
     * API URL
     * https://msdn.microsoft.com/en-us/office/office365/api/complex-types-for-mail-contacts-calendar#MessageResource
     * https://msdn.microsoft.com/en-us/office/office365/api/extended-properties-rest-operations
     */

    public static void main(String[] args) throws Exception {
        send();
    }

    private static void send() throws Exception {
        Map<String, Object> message = new HashMap<>();
        message.put("Subject", "Some Sample Subject");
        message.put("Body", getBody());
        addRecipients(message);
        addCustomHeader(message);
        addAttachment(message);

        Map<String, Map> messagePayload = new HashMap<>();
        messagePayload.put("Message", message);

        Gson gson = new Gson();
        String messageAsJson = gson.toJson(messagePayload);

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        headers.add("Content-Type: application/json");
        headers.add("Content-Length: " + messageAsJson.length());

        String url = "https://outlook.office.com/api/v2.0/me/sendmail";
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, messageAsJson, headers);
        System.out.println("STATUS_CODE=" + response.httpCode);
        if (response.httpCode == 202) {
            System.out.println("MESSAGE SENT\r\n\r\nTRY TO RETRIEVE MAIL SENT");
            filterMessageSent();
        }
        else {
            System.out.println(response);
        }
    }

    private static void filterMessageSent() throws Exception {
        String query = "SingleValueExtendedProperties/Any" +
                URLEncoder.encode("(ep: ep/PropertyId eq 'String {" + mailUUID + "} Name CUSTOM_HEADER_1' and ep/Value eq 'CUSTOM_HEADER_1_VALUE_" + mailUUID + "')", "UTF-8");
        String select = "Id,InternetMessageId";
        String url = "https://outlook.office.com/api/v2.0/me/messages?$filter=" + query + "&$select=" + select;

        List<String> headers = new ArrayList<>();
        headers.add("Authorization: Bearer " + OFFICE_ACCESS_TOKEN);
        headers.add("Accept: application/json");
        JavaSendMailUsingOffice365OAuth.Response response = executeSend(url, "", headers);
        if (response.httpCode == 200) {
            Map result = new Gson().fromJson(response.httpResponse, Map.class);
            result = (Map) ((List) result.get("value")).get(0);
            System.out.println("UNIQUE_OFFICE_MAIL_ID_OF_SEND_EMAIL=" + result.get("Id"));
            System.out.println("UNIQUE_MESSAGE_ID_OF_SEND_EMAIL=" + result.get("InternetMessageId"));
        }
    }

    private static void addCustomHeader(Map<String, Object> message) {
        List<Map> list = new ArrayList<>();
        mailUUID = UUID.randomUUID().toString();

        Map<String, String> val1 = new HashMap<>();
        val1.put("PropertyId", "String {" + mailUUID + "} Name CUSTOM_HEADER_1");
        val1.put("Value", "CUSTOM_HEADER_1_VALUE_" + mailUUID);

        list.add(val1);

        message.put("SingleValueExtendedProperties", list);
    }

    private static JavaSendMailUsingOffice365OAuth.Response executeSend(String url, String messageAsJson, List<String> headers) throws Exception {
        int httpCode = 0, timeOutMilli = 1000 * 30;;
        String httpResponse = "", responseMessage = "";

        HttpURLConnection connection = null;
        try {
            System.setProperty("https.protocols", "TLSv1.1,SSLv3,SSLv2Hello");
            connection = (HttpURLConnection) new URL(url).openConnection();
            if (messageAsJson.length() > 0) {
                connection.setRequestMethod("POST");
            }
            else {
                connection.setRequestMethod("GET");
            }
            connection.setDoOutput(true);
            connection.setConnectTimeout(timeOutMilli);
            connection.setReadTimeout(timeOutMilli);
            connection.setRequestProperty("Pragma", "no-cache");

            for (int i = 0; i < headers.size(); i++) {
                String header = headers.get(i);
                connection.setRequestProperty(header.substring(0, header.indexOf(":")), header.substring(header.indexOf(":") + 1));
            }

            if (messageAsJson.length() > 0) {
                connection.setDoInput(true);
                OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
                streamWriter.write(messageAsJson);
                streamWriter.flush();
                streamWriter.close();
            }

            httpCode = connection.getResponseCode();
            responseMessage = connection.getResponseMessage();
            InputStream inputStream = null;

            if (httpCode >= 200 && httpCode <= 399) {
                inputStream = connection.getInputStream();
            }
            else {
                inputStream = connection.getErrorStream();
            }

            if (inputStream != null) {
                Writer writer = new StringWriter();
                char[] buffer = new char[1024];
                Reader reader = new BufferedReader(new InputStreamReader(inputStream));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
                httpResponse = writer.toString();
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
            responseMessage = ex.getMessage();
        }
        return new JavaSendMailUsingOffice365OAuth.Response(httpCode, responseMessage, httpResponse);
    }

    private static Map<String, Object> getBody() throws Exception {
        Map<String, Object> body = new HashMap<>();

        body.put("ContentType", "HTML");
        body.put("Content", new String("<DIV><B>HTML BODY CONTENT</B></DIV>".getBytes(), "UTF-8"));

        return body;
    }

    private static void addRecipients(Map<String, Object> message) {
        Map<String, Map> recipientMap = new HashMap<>();
        Map<String, String> recipientAddress = new HashMap<>();
        recipientAddress.put("Address", "pritom@xxxxx.com");
        recipientMap.put("EmailAddress", recipientAddress);

        List<Map> recipients = new ArrayList<>();
        recipients.add(recipientMap);

        message.put("ToRecipients", recipients);
    }

    private static void addAttachment(Map<String, Object> message) throws Exception {
        List<Map> attachments = new ArrayList<>();

        File file = new File("src/com/pkm/office_oauth/Attachment_Image_1.png");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        file = new File("src/com/pkm/office_oauth/Attachment_Pdf_1.pdf");
        fileInputStream = new FileInputStream(file);
        toByte = new byte[(int) file.length()];
        fileInputStream.read(toByte);
        fileInputStream.close();

        Map<String, Object> attachment = new HashMap<>();
        attachment.put("@odata.type", "#Microsoft.OutlookServices.FileAttachment");
        attachment.put("Name", file.getName());
        attachment.put("ContentBytes", encodeBase64(toByte));

        attachments.add(attachment);
        message.put("Attachments", attachments);
    }

    private static String encodeBase64(byte[] bytes) throws Exception {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encodeBuffer(bytes);
    }

    private static class Response {
        int httpCode = 0;
        String httpResponse = "", responseMessage = "";

        public Response(int httpCode, String responseMessage, String httpResponse) {
            this.httpCode = httpCode;
            this.responseMessage = responseMessage;
            this.httpResponse = httpResponse;
        }

        public String toString() {
            Map<String, Object> output = new HashMap<>();
            output.put("httpCode", httpCode);
            output.put("responseMessage", responseMessage);
            output.put("httpResponse", httpResponse);
            return new Gson().toJson(output);
        }
    }
}

Sunday, December 18, 2016

Send Email Using Google OAuth & Java

Download source code & required jars from here

For get access token & google user id click here


package com.pkm.google_auth;

import com.google.api.client.googleapis.GoogleUtils;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.MessagePartHeader;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import java.util.Properties;

/**
 * Created by pritom on 18/12/2016.
 */
public class SendMail {
    private static final String USER_ID = "118224585672607576118";
    private static final String ACCESS_TOKEN = "ya29.Ci-4A700L53csid7qv6786780mbRqI8hdwesj7H2RSRnBizwfWFUY0pzYsx_xa-XZA";

    public static void main(String[] args) throws Exception {
        sendMail();
    }

    private static void sendMail() throws Exception {
        Properties props = new Properties();
        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

        });
        MimeMessage message = new MimeMessage(mailSession);

        message.setSubject("Test subject", "UTF-8");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("pritom@xxxxx.com", "Pritom Kumar"));

        Multipart multipart = new MimeMultipart();
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent("<DIV><B>BOLD HTML BODY</B></DIV>", "text/html");
        multipart.addBodyPart(messageBodyPart);

        message.addHeader("CUSTOM_HEADER_1", "CUSTOM_HEADER_1_VALUE");
        message.addHeader("CUSTOM_HEADER_2", "CUSTOM_HEADER_2_VALUE");

        message.setContent(multipart );

        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();

        com.google.api.services.gmail.model.Message email = createMessageWithEmail(message);
        email = gmail.users().messages().send(USER_ID, email).execute();
        String emailID = email.getId(), messageID = getUniqueMessageIDByEMailId(emailID);
        System.out.println("EMAIL_SEND_WITH_GOOGLE_MAIL_ID=" + emailID);
        System.out.println("EMAIL_SEND_WITH_UNIQUE_MAIL_ID=" + messageID);
    }

    private static String getUniqueMessageIDByEMailId(String emailID) throws Exception {
        GoogleCredential credential = new GoogleCredential().setAccessToken(ACCESS_TOKEN);
        Gmail gmail = new Gmail.Builder(_createHttpTransport(), _createJsonFactory(), credential).build();
        com.google.api.services.gmail.model.Message message = gmail.users().messages().get(USER_ID, emailID).execute();
        for (MessagePartHeader messagePartHeader : message.getPayload().getHeaders()) {
            if (messagePartHeader.getName().equalsIgnoreCase("Message-ID")) {
                emailID = messagePartHeader.getValue().substring(1, messagePartHeader.getValue().length() - 1);
            }
        }
        return emailID;
    }

    private static com.google.api.services.gmail.model.Message createMessageWithEmail(MimeMessage email) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        com.google.api.services.gmail.model.Message message = new com.google.api.services.gmail.model.Message();
        message.setRaw(encodedEmail);
        return message;
    }

    private static HttpTransport _createHttpTransport() throws Exception {
        return new NetHttpTransport.Builder()
                .trustCertificates(GoogleUtils.getCertificateTrustStore())
                .build();
    }

    private static JsonFactory _createJsonFactory() {
        return new JacksonFactory();
    }
}

Thursday, November 24, 2016

Send email using Php & Outlook / Office 365 using Oauth connection

To get oauth access token & other information used in this code snippet visit:
http://pritomkumar.blogspot.com/2016/11/write-php-app-to-get-outlook-office-365.html

Code snippet to send email using php via Office 365 account & oauth


<?php
session_start();
init();

if(isset($_POST["send"])) {
    $attachments = array();
    for($i = 0; $i < 6; $i++) {
        if(strlen(trim($_FILES["files"]["name"][$i])) > 0) {
            $content = base64_encode(file_get_contents($_FILES["files"]["tmp_name"][$i]));
            $attachment = array(
                "@odata.type" => "#Microsoft.OutlookServices.FileAttachment",
                "Name" => $_FILES["files"]["name"][$i],
                "ContentBytes" => $content
            );
            array_push($attachments, $attachment);
        }
    }

    $to = array();
    $toFromForm = explode(";", $_POST["to"]);
    foreach ($toFromForm as $eachTo) {
        if(strlen(trim($eachTo)) > 0) {
            $thisTo = array(
                "EmailAddress" => array(
                    "Address" => trim($eachTo)
                )
            );
            array_push($to, $thisTo);
        }
    }
    if (count($to) == 0) {
        die("Need email address to send email");
    }

    $request = array(
        "Message" => array(
            "Subject" =>$_POST["subject"],
            "ToRecipients" => $to,
            "Attachments" => $attachments,
            "Body" => array(
                "ContentType" => "HTML",
                "Content" => utf8_encode($_POST["message"])
            )
        )
    );

    $request = json_encode($request);
    $headers = array(
        "User-Agent: php-tutorial/1.0",
        "Authorization: Bearer ".$_SESSION["access_token"],
        "Accept: application/json",
        "Content-Type: application/json",
        "Content-Length: ". strlen($request)
    );

    $response = runCurl($_SESSION["api_url"], $request, $headers);
    echo "<pre>"; print_r($response); echo "</pre>";
    /* if $response["code"] == 202 then mail sent successfully */
}
else {
?>
<form method="post" enctype="multipart/form-data" accept-charset="ISO-8859-1">
<table style="width: 1000px;">
    <tr>
        <td style="width: 150px;">To</td>
        <td style="width: 850px;"><input type="text" name="to" required value="" style="width: 100%;"/></td>
    </tr>
    <tr>
        <td>Subject</td>
        <td><input type="text" name="subject" required value="Some sample subject on <?php echo date("d/m/Y H:i:s"); ?>" style="width: 100%;"/></td>
    </tr>
    <tr>
        <td>Files</td>
        <td>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
            <input type="file" name="files[]"/>
        </td>
    </tr>
    <tr>
        <td style="vertical-align: top;">Message</td>
        <td><textarea name="message" required style="width: 100%; height: 600px;"></textarea></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" name="send" value="Send"/></td>
    </tr>
</table>
</form>
<?php
}

function init() {
    $_SESSION["scopes"] = array("offline_access", "openid", "https://outlook.office.com/mail.send");

    $_SESSION["api_url"] = "https://outlook.office.com/api/v2.0/me/sendmail";

    $_SESSION["access_token"] = "eyJ0eXAiOiJKV1QidfsdfsdfsdfSUzI1NiIsIng1dCI6IlJyUXF1OXJ5ZEJWUldtY29jdVhVYjIwSEdSTSIsImtpZCI6IlJyUXF1OXJ5ZEJWUldtY29jdVhVYjIwSEdSTSJ9.eyJhdWQiOiJodHRwczovL291dGxvb2sub2ZmaWNlLmNvbSIsImlzcyI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzdkOTAzZjM5LTkxZGYtNGVmMS04ZDY0LTcxNDMwOTlhMTVmMC8iLCJpYXQiOjE0Nzk5NjE2NjAsIm5iZiI6MTQ3OTk2MTY2MCwiZXhwIjoxNDc5OTY1NTYwLCJhY3IiOiIxIiwiYW1yIjpbInB3ZCJdLCJhcHBpZCI6ImRhOGE1NGQ4LTg2YjUtNDE5Ni05ODFlLWUzMWVmYTNmM2Q1OSIsImFwcGlkYWNyIjoiMSIsImZhbWlseV9uYW1lIjoiQmlsbCIsImdpdmVuX25hbWUiOiJBdXRvIiwiaXBhZGRyIjoiMTAzLjQuMTQ2LjE4NiIsIm5hbWUiOiJBdXRvIEJpbGwiLCJvaWQiOiI5NGM1NTZlMy1jYmM1LTQxMTItYWJhZi0yMmUxZDVkNWU2ZjQiLCJwbGF0ZiI6IjMiLCJwdWlkIjoiMTAwMzAwMDA5QzcyRTlGRiIsInNjcCI6Ik1haWwuUmVhZCBNYWlsLlNlbmQiLCJzdWIiOiJ4SF9JNzl0bFRwbGI0WG41RktKSHZ6VTBkU2pJOUNBaDVCaElWTnljMTBNIiwidGlkIjoiN2Q5MDNmMzktOTFkZi00ZWYxLThkNjQtNzE0MzA5OWExNWYwIiwidW5pcXVlX25hbWUiOiJhdXRvYmlsbEB3ZWJhbGl2ZS5jb20uYXUiLCJ1cG4iOiJhdXRvYmlsbEB3ZWJhbGl2ZS5jb20uYXUiLCJ2ZXIiOiIxLjAifQ.a9RnBzxlChE8-_kfTcYuQy2lbpVsZOKIpn-fmSjePi5oiX4aPL-SZ6xL9rwdjL4SWeOyiDLHmVs3jhEbHkEIZhD4aqzbvqTovQOUluyHOAHVjQJyRc6AV6g-WP4jmbCDVOKFvvq9llZ13Srihvua1wFCM5z-nDZsIVY0LzTeew8-ZTM5trVEG9QtyR_UmlgLgwbIOl9PWz0MvFcCLbFiZQ8-1zGje8oL_fbm8vFtRdP_bNS6OzyatupFvAQRM4RhFQYHhuxKCVzI35JoEWfhHtUZAReTYwRfBULEJuT_CIkC0G7DyWJR1IRVnaYSWagvj93tOZtIaU-OMSsovmYEtg";
}

function runCurl($url, $post = null, $headers = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, $post == null ? 0 : 1);
    if($post != null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    if($headers != null) {
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    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();
    }
    return array("code" => $http_code, "response" => $response);
}
?>

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';?>