Using Java mail Pop3 cannot seem to delete emails from Gmail - java

I have a java program that acts as a POP3 client using javax.mail. I am able to list and retrieve the contents of a Gmail inbox no problem. However, I cannot seem to delete emails. Here is the (important parts of the) code:
POP3Store sto=... another method creates and connects the POP3Store
Folder ibx=sto.getFolder("INBOX");
ibx.open(Folder.READ_WRITE);
Message[] msgarr=ibx.getMessages();
for(int mi=0; mi<msgarr.length; mi++) {
...do stuff with the message
msgarr[mi].setFlag(Flags.Flag.DELETED, true);
}
ibx.close(true); //folder.close(true) indicates to expunge the folder
sto.close();
After running this and seeing it handle each message, I go into Gmail and the emails are still there, and even showing as unread. If I re-run the java client, it will see and handle the same emails.
This same code happily deletes emails from an exchange server.
How can I get Gmail to delete emails?

Gmail handles POP deletion specially.
You can configure what Gmail should do when a message is deleted through POP in Gmail Settings, on the Forwarding and POP / IMAP tab.

As SLaks says, Gmail is a special case where it has its own settings for controlling deletion that override whatever the client wants to do.
It can be edited in the Forwarding and POP / IMAP
However, I want to add that for a message to be considered "downloaded" by Gmail, you need to have retrieved the content of each message, and in the case of multipart message types, the content of each part within that message.
Here's some example code that I use to force the deletion of unwanted messages from Gmail:
// Grab the content to get the email off the server
// folder is of type javax.mail.Folder and is already in the correct state to get messages from the mail store (Gmail)
Message msg = folder.getMessage(1);
Multipart multipart = (Multipart) msg.getContent();
int partcount = multipart.getCount();
for (int count = 0; count < partcount; count++) {
multipart.getBodyPart(count);
}

If you prepend "recent:" in your pop3 username you will solve.
Example: recent:yourusername#gmail.com
This connects to gmail using Recent Mode

Related

send email to generic ID in lotus notes using notesFactory in java

Their is a requirement in a project to send emails from java application through lotus notes.
Note: the domino server is installed on client server.
Currently i am able to send email using notesFactory on my local machine.using notes.jar file
Which accesses the user by .nsf by its password.
I.e creating secure connection by password.
And gtting database object by calling
Session.getdatabase(null,"user.nsf")
Its perfectly working.
But for some types of emails the client have shared a generic id...(link) over an email... By clicking on that link the generic mail box opens under active user. In separate tab... Through which we can send emails.
But have not shared their .nsf path or id or password.
It directly opens by clicking on that link.
Now i want to access that generic id in notesfactory session
I tried to keep open that id and then running my code...but still it sends email through active user itself.
And client is not ready to share the id and password details of that user. Not the id file is getting generated in our local machine.
Is their any way to send emails through that id?
If anyone want code i am using..ill share.
But for some types of emails the client have shared a generic
id...(link) over an email... By clicking on that link the generic mail
box opens under active user. In separate tab... Through which we can
send emails.
That does not sound like a "shared id", it sounds more like a mail database with the ACL set to give a group of users access.
When you send an email from within Notes (no matter if it is through the UI or through code), the actual logged in user is used as the sender. It is intentionally by design, to prevent users from spoofing the sender.
There is an unsupported way to fake the sender address, by dropping the email directly into mail.box, but that should only be done by someone know what they are doing.
I wrote a script library several years ago, intended to help sending emails. It includes the ability to set the sender address. You can find it on my blog, it's free to use. But I would not recommend you using it without first understanding what the code is doing.
Here is the relevant part of the code:
Set mailbox = New NotesDatabase(mailservername,"mail.box")
If mailbox.Isopen = False Then
Print "mail.box on " & mailservername & " could not be opened"
Exit Sub
End If
Set me.maildoc = New NotesDocument(mailbox)
Call me.maildoc.ReplaceItemValue("Form","Memo")
Set me.body = New NotesRichTextItem(maildoc,"Body")
Call maildoc.ReplaceItemValue("Principal", me.p_principal)
' If principal is set, we want to fix so mail looks like
' it is coming from that address, need to set these fields
Call maildoc.ReplaceItemValue("From", me.p_principal)
Call maildoc.ReplaceItemValue("Sender", me.p_principal)
Call maildoc.ReplaceItemValue("ReplyTo", me.p_principal)
Call maildoc.ReplaceItemValue("SMTPOriginator", me.p_principal)
Call maildoc.ReplaceItemValue("PostedDate",Now())
If me.p_principal<>"" Then
Call maildoc.Save(True,False) ' Save in mail.box
Else
Call maildoc.Send(True) ' Send mail normally
End If
You use the Principal field to set the sender address.

how to trigger a gcm to send a push notification to android device(using java server)

I am very new to java server side development, i have followed this link [http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/][1] and successfully implemented GCM with my android device, the problem is dont know how to trigger the GCM server while the content is updated in my db,i need to notify each and every update of my db to the user, am i need to watch the db using timer task something like that or is there any default solution to keep track of db ?
My Server side code :
regId = "my registration id";
String userMessage = request.getParameter("message");
Sender sender = new Sender(GOOGLE_SERVER_KEY);
Message message = new Message.Builder().timeToLive(30)
.delayWhileIdle(true).addData(MESSAGE_KEY, userMessage).build();
result = sender.send(message, regId, 1);
have tried with many solution but till now not getting exact solution, Suggestion, ideas or related links are most welcome
Thanks in advance
Without knowing the specific functionality of your server and app, I can only offer a general solution.
Each process in your server that performs DB updates that have to be pushed to some Android devices via GCM can write the messages and the registration IDs to some kind of queue.
Then you can have another process (or processes) that would consume the queue of GCM messages, and send them to Google. These processes can handle failures (retry sending the messages in case of temporary failures), and update your database of registration IDs if they receive responses with canonical registration IDs or errors such as InvalidRegistration or NotRegistered.

Spring IAMP Mail receiver not reading all emails everytime [duplicate]

I have a piece of code which uses spring integration's IMAP adapter to poll an inbox to read all incoming emails which are unread and that works perfectly. But if I open any email message and and then mark it as "unread" in my outlook inbox the poller doesn't fetch the marked email.
I can use the pop3 adapter which fetches all the email, but deletes them afterwords, but I want to keep the emails in my inbox and I want the poller to fetch all the email which are unseen.
Any suggestions to handle this problem? I been searching and reading articles on email adapters but didn't find anything useful.
Thanks in advance.
Looks like you need custom 'search-term-strategy'. From Spring Integration (SI) documentation:
By default, the ImapMailReceiver will search for Messages based on the default SearchTerm which is All mails that are RECENT (if supported), that are NOT ANSWERED, that are NOT DELETED, that are NOT SEEN and have not been processed by this mail receiver (enabled by the use of the custom USER flag or simply NOT FLAGGED if not supported). Since version 2.2, the SearchTerm used by the ImapMailReceiver is fully configurable via the SearchTermStrategy which you can inject via the search-term-strategy attribute. SearchTermStrategy is a simple strategy interface with a single method that allows you to create an instance of the SearchTerm that will be used by the ImapMailReceiver.
And here is a post from SI forum with funtastic Oleg's explanation: Server does not support RECENT or USER flags
And here you can find SI DefaultSearchTermStrategy: it's a place to determine how you should implement your own strategy. I guess, you case is:
This email server does not support RECENT flag, but it does support USER flags which will be used to prevent duplicates during email fetch.
Switch SI-mail logging level to DEBUG and take a look, which flag supports your email server.

Dealing with failed email sending with SMTP-JAVA

I am working on a service that sends out emails using SMTP. I set my SMTP properties this way:
property.setProperty("mail.transport.protocol", "smtp");
property.setProperty("mail.smtp.host", mailHost);
property.setProperty("mail.from", "xyz#gmail.com");
It also works for successful cases. However, when the email sending process fails, I want a notification sent to another one of our customer care email address(say, CC#gmail.com)..
How do I accomplish this. Is there any property among SMTP properties that lets me give like a "failure email address" so that it send a notification to that address, if a failure occurs
Bounced emails usually go back to the From: address, so you might change this to, say, "CC#gmail.com". This is also nice because it allows your customers back to you by just hitting "reply" in their mail client.

Determining which Gmail Tab an email is placed under, using the Javamail API

I am working on application that can determine which Gmail Tab an email is placed under (ie Social, Promotions, etc). Is there any way of determining which Gmail Tab an email is placed into with the Javamail API? Or are there some other applications that can determine this?
Thanks in advance.
It is not possible to determine the category/tab with the Javamail API because Google do not integrate the information with the IMAP protocol. The category/tab is only available via Google's proprietary GMail APIs.
In the GMail settings under labels, I was able to get categories to show up as folders in the GMail web client by clicking on 'show' next to categories, however they did not come down in the IMAP request. It must be by design because there is no "Show in IMAP" option provided for the categories.
In the existing answer it is mentioned that the GMail IMAP extensions can be used to access X-GM-THRID and X-GM-LABELS
These extensions are explained in Google's GMail IMAP docs:
https://developers.google.com/gmail/imap/imap-extensions
X-GM-LABELS -> "Gmail treats labels as folders for the purposes of IMAP."
a010 FETCH 1:4 (X-GM-LABELS)
1 FETCH (X-GM-LABELS (\Inbox \Sent Important "Muy Importante"))
2 FETCH (X-GM-LABELS (foo))
3 FETCH (X-GM-LABELS ())
4 FETCH (X-GM-LABELS (\Drafts))
a010 OK FETCH (Success)
X-GM-THRID -> "Gmail provides a thread ID to associate groups of messages in the same manner as in the Gmail web interface."
a008 FETCH 1:4 (X-GM-THRID)
1 FETCH (X-GM-THRID 1278455344230334865)
2 FETCH (X-GM-THRID 1266894439832287888)
3 FETCH (X-GM-THRID 1266894439832287888)
4 FETCH (X-GM-THRID 1266894439832287888)
a008 OK FETCH (Success)
But neither of these extensions specifies the category to which an email belongs.
There are however two alternative solutions that will allow Javamail to work with categories indirectly:
Use a filter that associates labels with each category -> Causes an IMAP folder to be created for each category
Create a filter and associate it with "Skip inbox" to exclude certain emails from coming down in the IMAP request if that is your goal
Procedure for changing categories into labels/IMAP-folders:
Go to GMail Settings
Click on "See All Settings"
Click on "Filters and Blocked Addresses"
Click on "Create new Filter"
On the line "Includes the words" enter "category:primary"
Click "Create the Filter"
Tick "Apply the Label"
Choose "New label..."
Enter the label name
[This will be the IMAP folder name]
Screenshots for the procedure:
The procedure for skipping the inbox
Same procedure as above
In step 7, choose "Skip in the inbox" instead of "Apply the Label"
The list of possible categories to filter on:
category:primary
category:social
category:promotions
category:forums
category:updates
The standard IMAP/SMTP capabilities of JavaMail API & Gmail API together were quite enough, even to deal with the labels. But to fetch custom Gmail attributes X-GM-THRID and X-GM-LABELS also, have a look at Gmail Imap Extensions.
In order to fetch a list of messages from Gmail you must be implementing standard javamail profile fetch:
folder.fetch(msgs, stdFetchProfile);
Now to fetch the list of tags/tabs/labels from Gmail, make a call to custom method using IMAPFolder’s doCommand()
final MessageSet[] mSets = MessageSet.createMessageSets(mns);
((IMAPFolder) folder).doCommand(new IMAPFolder.ProtocolCommand() {
#Override
public Object doCommand(IMAPProtocol p) throws ProtocolException {
try {
Response[] r = p.fetch(mSets, "X-GM-LABELS X-GM-THRID");
for (int i = 0; i < r.length; i++) {
if (!FetchResponse.class.isInstance(r[i]))
continue;
// Got a FetchResponse.
GmailFetchResponse gfr = new GmailFetchResponse(
((FetchResponse) r[i]).toString());
// Use gfr.getNumber() to get the msg number
for (int j = 0; j < gfr.getItemCount(); j++) {
Item item = gfr.getItem(j);
if (X_GM_LABELS.class.isInstance(item))
// get the labels
((X_GM_LABELS) item).x_gm_labels);
}
}
} catch (ProtocolException e) {
logError(e.getMessage(), e);
}
return null;
}
});
Then you need to do the re-parse using java-gmail-imap' parse() method.
Above implementation is excellently explained on following link.
Getting Gmail labels using javamail
Shishir

Categories

Resources