Receiving an email from outside into Adempiere


While Adempiere provides ways to send mails from within the processes as well as it provides explicit features for sending mail to the desired list of people. However, there are situations where customer want to send and receive mails using the ERP system itself. Sometimes they go one step ahead and they want to keep track of each and every communication by appropriate tagging. This is where Walking Tree has come up with enhancement in Adempiere to provide you a mailbox capability.

Purpose of this article is to explain you what do you need to know to be able to read a mail inside Adempiere. This is a PoC for downloading a mail from a mail server, which can be used inside the Adempiere, with slight modification:

Create One table for store the e-mail from outside to our database.

CREATE TABLE C_mail(

C_mail_ID         NUMERIC(10) PRIMARY KEY,

AD_user_ID        NUMERIC(10),

mail_from         VARCHAR(1000),

mail_to           VARCHAR(1000),

cc                VARCHAR(1000),

bcc               VARCHAR(1000),

date              TIMESTAMP WITHOUT TIME ZONE,

subject           VARCHAR(1000),

body              VARCHAR(10485760)

— And all the mandatory field required to work with Adempiere architecture.

)

 

ALTER TABLE C_mail

ADD CONSTRAINT FOREIGN KEY (AD_user_ID)

REFERENCES AD_user(AD_user_ID) ;

Fetch the mail from mail server and store into Adempiere using the following steps:

Write a class to read the mail from the mail server and store into our data base. As “MailReader.java”

 

package com.info.mail;

import java.sql.Timestamp;

import java.util.*;

 

import javax.activation.DataHandler;

import javax.mail.*;

import javax.mail.search.DateTerm;

import javax.mail.search.SentDateTerm;

 

 

public class MailReader

{

private Folder inbox;

private Mail mail;

private Timestamp latestMessageDate = null;

private Date sentDate;

private Message messages[];

private Properties props;

private Session session;

private Store store;

 

//Constructor of the class.

public MailReader(String protocol, String serverUrl, String userName, String password)

{

// Get the mail properties

props = System.getProperties();

 

mail = new Mail();

try

{

// Create the session and get the store for read the mail.

session = Session.getDefaultInstance(props, null);

 

store = session.getStore( protocol );

 

//Connect to the store.

store.connect( serverUrl, userName, password);

 

// Mention the folder name which you want to read.

inbox = store.getFolder("Inbox");

 

//Open the inbox using store.

inbox.open(Folder.READ_WRITE);

 

//  Get the latest messages date

latestMessageDate = mail.getMaxDate();

 

 

if (latestMessageDate != null)// Fetch the latest one

{

messages = inbox.search(new SentDateTerm( DateTerm.GT, new java.util.Date(latestMessageDate.getTime())));

}

else

messages = inbox.getMessages(); // Reading the message first time , Fetch all messages.

 

 

try

{

if( messages.length >0){

printAllMessages(messages);

}

else

System.out.println("No Unread msgs");

 

inbox.close(true);

store.close();

}

catch (Exception ex)

{

System.out.println("Exception arise at the time of read mail");

ex.printStackTrace();

}

}

catch (NoSuchProviderException e)

{

e.printStackTrace();

System.exit(1);

}

catch (MessagingException e)

{

e.printStackTrace();

System.exit(2);

}

 

catch ( Exception exception)

{

exception.printStackTrace();

System.exit(3);

}

}

 

public void printAllMessages(Message[] msgs) throws Exception

{

 

for (int i = 0; i < msgs.length; i++)

{

System.out.println("MESSAGE #" + (i + 1) + ":");

printEnvelope(msgs[i]);

}

}

 

/*  Print the envelope(FromAddress,ReceivedDate,Subject)  */

public void printEnvelope(Message message) throws Exception

{

 

Address[] address;

String from ="", to= "", cc="", bcc="" , content ="";

 

// FROM

if ((address = message.getFrom()) != null)

{

for (int j = 0; j < address.length; j++)

{

System.out.println("FROM: " + address[j].toString());

from = from+ address[j].toString();

}

}

// TO

if ((address = message.getRecipients(Message.RecipientType.TO)) != null)

{

for (int j = 0; j < address.length; j++)

{

System.out.println("TO: " + address[j].toString());

to = to+ address[j].toString();

}

}

//CC

if ((address = message.getRecipients(Message.RecipientType.CC)) != null)

{

for (int j = 0; j < address.length; j++)

{

System.out.println("CC: " + address[j].toString());

cc = cc+ address[j].toString();

}

}

//BCC

if ((address = message.getRecipients(Message.RecipientType.BCC)) != null)

{

for (int j = 0; j < address.length; j++)

{

System.out.println("BCC: " + address[j].toString());

bcc = bcc+ address[j].toString();

}

}

 

String subject = message.getSubject();

sentDate = message.getSentDate();

 

System.out.println("Subject : " + subject);

System.out.println("Received Date : " + sentDate.toString());

System.out.println("Content : " + content);

 

if( message.getContent() instanceof String)

content+= message.getContent().toString();

 

if( message.getContent() instanceof Multipart){

Multipart multipart = (Multipart) message.getContent();

content += "Content Type "+message.getContentType();

 

for (int x = 0; x < multipart.getCount(); x++) {

BodyPart bodyPart = multipart.getBodyPart(x);

 

String disposition = bodyPart.getDisposition();

 

if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {

System.out.println("Mail have some attachment : ");

content+= "Mail have some attachment : ";

 

DataHandler handler = bodyPart.getDataHandler();

System.out.println("file name : " + handler.getName());

content+= "file name : " + handler.getName();

} else {

System.out.println(bodyPart.getContent());

content+= bodyPart.getContent();

}

}

}

 

//set all the property of Mail

mail.setBcc(bcc);

mail.setCc(cc);

mail.setTo(to);

mail.setFrom(from);

mail.setDate(new Timestamp(sentDate.getTime()));

mail.setSubject(subject);

mail.setBody(content);

 

//Save into Database

mail.save();

}

 

public static void main(String args[])

{

 

new MailReader( < Protocol >, < Server URL >, < mail-id >, < password > );

 

}

}

 

 

// Mail.java

 

package com.info.mail;

import java.io.Serializable;

import java.sql.Blob;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.Timestamp;

import org.postgresql.Driver;

import java.sql.PreparedStatement;

import java.util.Random;

 

public class Mail  implements Serializable{

 

/**

*

*/

private static final long serialVersionUID = 1L;

private int mailId;

private int userId;

private Timestamp date;

private String subject;

private String from;

private String to;

private String cc;

private String bcc;

private String body;

private Connection connection;

private PreparedStatement preparedStatement;

private Statement statement;

private ResultSet resultSet;

 

 

public void setMailId(int mailId) {

this.mailId = mailId;

}

public void setUserId(int userId) {

this.userId = userId;

}

public void setDate(Timestamp date) {

this.date = date;

}

public void setSubject(String subject) {

this.subject = subject;

}

public static long getSerialversionuid() {

return serialVersionUID;

}

public int getMailId() {

return mailId;

}

public int getUserId() {

return userId;

}

public Timestamp getDate() {

return date;

}

public String getSubject() {

return subject;

}

public String getFrom() {

return from;

}

public String getTo() {

return to;

}

public String getCc() {

return cc;

}

public String getBcc() {

return bcc;

}

public String getBody() {

return body;

}

public void setFrom(String from) {

this.from = from;

}

public void setTo(String to) {

this.to = to;

}

public void setCc(String cc) {

this.cc = cc;

}

public void setBcc(String bcc) {

this.bcc = bcc;

}

public void setBody(String body) {

this.body = body;

}

 

 

 

//Constructor of the class

 

public Mail(){

setUserId(100);//Hard coded value will be handeled while implementation.

try{

Class.forName("org.postgresql.Driver");

connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/<database-name>",<db-user-id>,"<db-password>");

preparedStatement = connection.prepareStatement("insert into c_mail values( ?,?,?,?,?,?,?,?,? )");

statement = connection.createStatement();

}catch( Exception exception ){

 

System.out.print("exception"+exception);

 

}

 

}

public void save() throws Exception

{

preparedStatement.setInt(1, new Random().nextInt());//ID will be passed automatically by Adempiere.

preparedStatement.setInt(2, userId);

preparedStatement.setTimestamp(3, date);

preparedStatement.setString(4, subject);

preparedStatement.setString(5, from);

preparedStatement.setString(6, to);

preparedStatement.setString(7, cc);

preparedStatement.setString(8, bcc);

preparedStatement.setString(9, body);

 

preparedStatement.executeUpdate();

 

 

}

 

public Timestamp getMaxDate() throws Exception{

 

resultSet = statement.executeQuery("SELECT MAX(date) from c_mail where ad_user_id ="+userId );

if(resultSet.next())

return resultSet.getTimestamp(1);

else

return null;

}

 

}

Here in this class we are getting the mail from the server and displaying into the console as well as storing into the database. All you need to do is to convert the mail download function into an Adempiere process and download the mails periodically. Also, you may need to change the table structure to be able to meet your implementation specific need.

 

Hope you find this article and codes useful. Walking Tree is a leading provider of Adempiere based ERP implementation and if you need our professional services then do contact us with exact detail about your need.

 

Tagged with: , , ,
Posted in ADempiere

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

We Have Moved Our Blog!

We have moved our blog to our company site. Check out https://walkingtree.tech/index.php/blog for all latest blogs.

Sencha Select Partner Sencha Training Partner
Xamarin Authorized Partner
Recent Publication
%d bloggers like this: