I am getting a message in raw format . Then got the Mimemessage by
MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(emailBytes));
Now email.getSubject is returning right value but
email.getReceivedDate is null
Please explain this behaviour. Is this the right way to decode different parts of the mail
com.google.api.services.gmail.model.Message fullMessage = mService.users().messages().get(acct.sEmail, message.getId()).setFormat("raw").execute();
Properties props = new Properties();
idg.javax.mail.Session session = idg.javax.mail.Session.getDefaultInstance(props, null);
byte[] emailBytes = com.google.api.client.util.Base64.decodeBase64(fullMessage.getRaw());
try {
idg.javax.mail.internet.MimeMessage email = new idg.javax.mail.internet.MimeMessage(session, new ByteArrayInputStream(emailBytes));
Log.i("Received date","is" + email.getReceivedDate() + message.getId());
Log.i("subject", "is" + email.getSubject());
} catch (MessagingException e) {
e.printStackTrace();
}
yes you can use getReceivedDate() for MimeMessage and yes, ofcourse its the better way to retrieve the values for different parts of mail.
This is to retrieve MimeMessage:
Users MimeMessage
This is to get Different Properties of mail :MimeMessage Properties
Related
I'm learning Javamail these days following this website:
http://www.tutorialspoint.com/javamail_api/
I test the sending & added some extra stuff because it was on Android & it worked!
But things have changed completely when I tried to follow receiving email Tutorial which makes me wonder..
Is it possible to make this code :
https://www.tutorialspoint.com/javamail_api/javamail_api_fetching_emails.htm
works on android but using XML interface?!
You can use the following code:
public static void receiveEmail(String pop3Host, String storeType, user, String password) {
try {
//1) get the session object
Properties properties = new Properties();
properties.put("mail.pop3.host", pop3Host);
Session emailSession = Session.getDefaultInstance(properties);
//2) create the POP3 store object and connect with the pop server
POP3Store emailStore = (POP3Store) emailSession.getStore(storeType);
emailStore.connect(user, password);
//3) create the folder object and open it
Folder emailFolder = emailStore.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
//4) retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
//5) close the store and folder objects
emailFolder.close(false);
emailStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
call your method passing some parameters:
String host = "pop.gmail.com";//change accordingly
String mailStoreType = "pop3";
String username= "example#gmail.com";
String password= "xxxxx";//change accordingly
receiveEmail(host, mailStoreType, username, password);
Source: Steps for receiving the email using JavaMail API
With reference of that enter link description here
I have send message successfully but I want to send custom header as well because of get status which particular message has send to update user
public void sendInstantMessage(String number, String msgBody) {
String sipServer = "aaa.ggg.net";
String buddy_uri = "<sip:" + number + "#" + sipServer + ">";
BuddyConfig bCfg = new BuddyConfig();
bCfg.setUri(buddy_uri);
bCfg.setSubscribe(false);
MyBuddy myBuddy = new MyBuddy(bCfg);
SendInstantMessageParam prm = new SendInstantMessageParam();
prm.setContent(msgBody);
// prm.setUserData(value)
try {
myBuddy.create(account, bCfg);
myBuddy.sendInstantMessage(prm);
myBuddy.delete();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
By using `Token pj::SendInstantMessageParam::userData for link enter link description here
I want to send the userdata header, but how to sent that header??
Thanks
Finally I got the solution for sending SMS with custom header using pjsip-2.4
Here is the code
String msgBody = "sending message";
SendInstantMessageParam prm = new SendInstantMessageParam();
prm.setContent(msgBody);
SipHeader hName = new SipHeader();
hName.setHName("name");
hName.setHValue(uniqueId);
SipHeaderVector headerVector = new SipHeaderVector();
headerVector.add(hName);
SipTxOption option = new SipTxOption();
option.setHeaders(headerVector);
prm.setTxOption(option);
try {
myBuddy.sendInstantMessage(prm);
} catch (Exception e) {
e.printStackTrace();
}
I want to send an image with text to a follower using twitter4j. I am able to send a direct message like this:
twitter.sendDirectMessage(twitterID, message);
Now, I can't figure out how to send an image as direct message. I did this for posting a tweet, which works:
StatusUpdate status = new StatusUpdate(message);
status.setMedia(pathOfTheFileToSend);
twitter.updateStatus(status);
So is it possible to send a image as direct message in twitter with the library twitter4j?
Thanks in advance.
First it's worth noting what Twitter4j does. It provides a good abstraction and bindings to Twitter's REST API in Java.
If you look at Twitter's Direct Message Endpoint you will see that it does not currently provide a way to "attach" an image when sending a direct message.
This has been confirmed at Twitter Developers forums before:
We have no announced plans yet for providing a media upload endpoint
for direct messages.
I have found a way to attach an image to a DM that works for me in my java project, using the following code:
...
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
//Get the User ID from the Screen Name
User user = twitter.showUser("screenName"); //#Hec_KuFlow for example
long userId = user.getId();
//The message to send
String message = "Hi! this is the message";
//Upload the file and get the ID
File imageFile = new File("C:\\demo\\picture.png");
long[] mediaIds = new long[1];
UploadedMedia media = twitter.uploadMedia(imageFile);
mediaIds[0] = media.getMediaId();
DirectMessage directMessage = twitter.directMessages().sendDirectMessage(userId, message, mediaIds[0]) throws TwitterException;
...
Use following code to send an image with text
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setOAuthConsumerKey(context.getResources().getString(R.string.twitter_consumer_key));
configurationBuilder.setOAuthConsumerSecret(context.getResources().getString(R.string.twitter_consumer_secret));
configurationBuilder.setOAuthAccessToken(LoginActivity.getAccessToken((context)));
configurationBuilder.setOAuthAccessTokenSecret(LoginActivity.getAccessTokenSecret(context));
Configuration configuration = configurationBuilder.build();
Twitter twitter = new TwitterFactory(configuration).getInstance();
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file); // set the image to be uploaded here.
twitter.updateStatus(status);
For details explanation check this tutorial.
public void tweetPicture(File file, String message) throws Exception {
try{
StatusUpdate status = new StatusUpdate(message);
status.setMedia(file);
mTwitter.updateStatus(status);}
catch(TwitterException e){
Log.d("TAG", "Pic Uploading error" + e.getErrorMessage());
throw e;
}
}
OR you can refer this
I want to send direct message to user's followers using my android application.I have tried following code
String access_token = mSharedPreferences.getString(
Constants.PREF_KEY_OAUTH_TOKEN, "");
// Access Token Secret
String access_token_secret = mSharedPreferences.getString(
Constants.PREF_KEY_OAUTH_SECRET, "");
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setDebugEnabled(true);
builder.setOAuthConsumerKey(Constants.TWITTER_CONSUMER_KEY);
builder.setOAuthConsumerSecret(Constants.TWITTER_CONSUMER_SECRET);
builder.setOAuthAccessToken(access_token);
builder.setOAuthAccessTokenSecret(access_token_secret);
TwitterFactory tf = new TwitterFactory(builder.build());
Twitter twitter = tf.getInstance();
DirectMessage message = null;
try {
message = twitter.sendDirectMessage(
frndsDetails.get(position).getId(), "Hi");
System.out.println("Sent: " + message.getText()
+ " to #" + message.getRecipientScreenName());
} catch (TwitterException e) {
// TODO Auto-generated catch block
Log.e("Twitter exception", "" + e.getMessage());
e.printStackTrace();
}
But got following exception
02-26 13:48:16.287: E/Twitter exception(707): 404:The URI requested
is invalid or the resource requested, such as a user, does not exists.
Also returned when the requested format is not supported by the
requested method. 02-26 13:48:16.287: E/Twitter exception(707):
message - Sorry, that page does not exist 02-26 13:48:16.287:
E/Twitter exception(707): code - 34 02-26 13:48:16.397:
W/System.err(707): at android.view.View.performClick(View.java:3511)
Is there any other method for sending direct message.Please help me. Thanks in advance.
I have used following code in my application for sending direct messages to the followers. May be this can helpful to you.
StringBuilder builder = new StringBuilder();
builder.append("#").append(twitterFriendObj.screenName).append(" ");
Status status = twitter.updateStatus(builder+"Hi this is test message");
Here we need to send follower screen name to send direct message.
I am doing on task to retrieve gmails. I manage to retrieve with below codes. However, it retrieved received email from the earliest to latest emails in the gmail inbox. Is there a way to make it retrieved the latest mails? I intend to implement a way to retrieved the latest 20 mails only instead of retrieved all the mails in the inbox. Thanks in advance for the guidance.
public ArrayList<HashMap<String, String>> getMail(int inboxList){
Folder inbox;
/* Set the mail properties */
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com",username, password);
/* Mention the folder name which you want to read. */
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
/*Open the inbox using store.*/
inbox.open(Folder.READ_WRITE);
/* Get the messages which is unread in the Inbox*/
Message messages[];
if(recent){
messages = inbox.search(new FlagTerm(new Flags(Flag.RECENT), false));
}else{
messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
}
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try
{
printAllMessages(messages);
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);
}
Instead of using inbox.search() use
inbox.getMessages(int start,int end);
it will retrieve the range of messages.
To get the latest 20 mails use:
int n=inbox.getMessageCount();
messages= inbox.getMessages(n-20,n);
If you just want the last 20 messages, just ask for the last 20 message numbers,
or access the last 20 entries in the array returned by folder.getMessages().
Not that the order of messages in the mailbox is the order in which they arrived,
not the order in which they were sent.
Used the android.os.Message
static class DateCompare implements Comparator<Message> {
public int compare(Message one, Message two){
return one.getWhen().compareTo(two.getWhen());
}
}
............
DateCompare compare = new DateCompare();
Message messages[];
if(recent){
messages = inbox.search(new FlagTerm(new Flags(Flag.RECENT), false));
}else{
messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
}
List<Message> list = Arrays.asList(messages );
Collections.sort(list,compare);
List<Messsage> newList = list.subList(0,19);
hope this helps.