The FROM: address in my emails sent from java don't appear correctly. This is not running in an application server but from a main() call:
// Get system properties
final Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", "localhost");
// Get the default Session object.
final Session session = Session.getDefaultInstance(properties);
// Create a default MimeMessage object.
final MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress("support#mydomain.com"));
// Set To: header field of the header.
message.setRecipients(javax.mail.Message.RecipientType.TO, "you#you.com");
// Set Subject: header field
message.setSubject("Your pants are on fire!");
message.setSentDate(new Date());
// Now set the actual message
message.setText("Take me to the bridge. ow!");
// Send message
Transport.send(message);
Here's the raw received email. Two things to note: the linux username under which the java process runs is mungo. The linux servername/hostname is servername. The domain is santamaria.com. These have been changed from their original to protect the guilty.
My question is: why isn't Return-Path support#mydomain.com and how can I make it so? Secondarily, how can I add a friendly name? e.g. Roger Earl <support#mydomain.com>
Delivered-To: you#you.com
Received: by 10.70.125.201 with SMTP id ms9csp51721pdb;
Sat, 22 Nov 2014 07:38:22 -0800 (PST)
X-Received: by 10.140.84.71 with SMTP id k65mr15089869qgd.76.1416670702208;
Sat, 22 Nov 2014 07:38:22 -0800 (PST)
Return-Path: <mungo#servername.santamaria.com>
Received: from servername.santamaria.com (servername.santamaria.com. [201.74.27.72])
by mx.google.com with ESMTPS id z90si10522625qgd.46.2014.11.22.07.38.21
for <you#you.com>
(version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
Sat, 22 Nov 2014 07:38:22 -0800 (PST)
Received-SPF: none (google.com: mungo#servername.santamaria.com does not designate permitted sender hosts) client-ip=201.74.27.72;
Authentication-Results: mx.google.com;
spf=none (google.com: mungo#servername.santamaria.com does not designate permitted sender hosts) smtp.mail=mungo#servername.santamaria.com
Received: from servername.santamaria.com (localhost [127.0.0.1])
by servername.santamaria.com (8.14.4/8.14.4) with ESMTP id sAMFcLkq012340
for <you#you.com>; Sat, 22 Nov 2014 15:38:21 GMT
From: RogerEarl <mungo#servername.santamaria.com>
Date: Sat, 22 Nov 2014 15:38:21 +0000 (UTC)
To: you#you.com
Message-ID: <1542856295.1.1416670701712.JavaMail.mungo#servername.santamaria.com>
Subject: Your pants are on fire!
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Take me to the bridge. ow!
UPDATE
The working code looks like this:
properties.setProperty("mail.smtp.from", "support#mydomain.com");
message.setFrom(new InternetAddress("support#mydomain.com", "My Friendly Support Name");
The InternetAddress class includes a constructor that allows you to set a "personal name" along with the email address; read the javadocs.
The Return-Path header is set by the receiving mail server, probably based on the "envelope from" address. Set the mail.smtp.from property to the address you want to use.
Related
I have been trying to use different Java OAuth libraries to get request and access token from Twitter API. Finally, I have come to use Scribe as one of the most stable libraries for this matter. However, I have not been able to get this to work with Twitter on the first step which is getting the access token:
twitterOAuthService = new ServiceBuilder(twitterOauthConsumerKey)
.apiSecret(twitterOauthConsumerKey).debug().callback(callback).build(
TwitterApi.instance());
OAuth1RequestToken requestToken = twitterOAuthService.getRequestToken();
It throws the following exception:
Response{code=401, message='Authorization Required', body='null', headers={date=Tue, 05 Nov 2019 07:06:34 GMT, null=HTTP/1.1 401 Authorization Required, server=tsa_l, content-length=64, expires=Tue, 31 Mar 1981 05:00:00 GMT, x-response-time=166, x-frame-options=SAMEORIGIN, www-authenticate=OAuth realm="https://api.twitter.com", x-transaction=00e2c19300b2d1ab, strict-transport-security=max-age=631138519, pragma=no-cache, set-cookie=guest_id=v1%3A157293759473549885; Max-Age=63072000; Expires=Thu, 4 Nov 2021 07:06:34 GMT; Path=/; Domain=.twitter.com, last-modified=Tue, 05 Nov 2019 07:06:34 GMT, x-xss-protection=0, x-content-type-options=nosniff, content-disposition=attachment; filename=json.json, x-connection-hash=badf004485a6d713a29ed3f90de9e981, x-twitter-response-tags=BouncerCompliant, content-type=application/json; charset=utf-8, cache-control=no-cache, no-store, must-revalidate, pre-check=0, post-check=0, status=401 Unauthorized}}
I can see that the Authorization header is set properly:
Authorization -> OAuth oauth_callback="http%253A%252F%252F127.0.0.1%253A3000%252Fsettings", oauth_consumer_key="8hupaLbXA2s792EzU8DIE6K", oauth_nonce="2929183554", oauth_signature="s%2BRMAninTESJqJg92BuEA8h3E%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1572936780", oauth_version="1.0"
I have tested the below approaches as they were suggested in different places:
Ensure Authorization header is sorted alphabetically!
Ensure that the timestamp is set properly
Ensure that the consumer secret and consumer key are set properly
Ensure that the encoding of oauth_signature (percent encoding) and call_back is set properly
I have run out of any other scenarios and I am not even sure if I can use Scribe library for Twitter. I would appreciate it if someone could help me to address this issue.
I am trying to send multiple mails using JAVA Mail -
When I add a single Recipient -
message.addRecipient(Message.RecipientType.TO, new InternetAddress(“abc#xyz.com”));
It works fine, but not when I add multiple email addresses -
Here is the code
message.addRecipient(Message.RecipientType.TO, new InternetAddress(“abc#xyz.com”));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(“def#xyz.com"));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(“ghi#xyz.com"));
message.addRecipient(Message.RecipientType.CC, new InternetAddress(“jkl#xyz.com"));
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(“mno#xyz.com"));
The mail is sent and received, but when I check the email of abc#xyz.com I can't see that the email has also been sent to def#xyz.com or vise versa. Neither I can see CC in the list.
Mail details from abc#xyz.com
from: xyz#xyz.com
to: abc#xyz.com
date: Thu, Sep 8, 2016 at 4:38 PM
subject: Test
Mail details from def#xyz.com
from: xyz#xyz.com
to: def#xyz.com
date: Thu, Sep 8, 2016 at 4:38 PM
subject: Test
Mail details from ghi#xyz.com
from: xyz#xyz.com
to: ghi#xyz.com
date: Thu, Sep 8, 2016 at 4:38 PM
subject: Test
Mail details from jkl#xyz.com
from: xyz#xyz.com
to: jkl#xyz.com
date: Thu, Sep 8, 2016 at 4:38 PM
subject: Test
I tried changing the logic a little, but same result -
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(“abc#xyz.com, def#xyz.com"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse(“ghi#xyz.com, jkl#xyz.com”));
message.addRecipient(Message.RecipientType.BCC, InternetAddress.parse(“mno#xyz.com"));
I am expecting to see the details as -
from: xyz#xyz.com
to: abc#xyz.com, def#xyz.com
cc: ghi#xyz.com, jkl#xyz.com
date: Thu, Sep 8, 2016 at 4:38 PM
subject: Test
You should try:
Address[] toArray = new Address[] {InternetAddress.parse("abc#xyz.com"),
InternetAddress.parse("def#xyz.com")};
message.addRecipients(Message.RecipientType.TO, toArray);
To prevent any mistakes and surprises, I would recommend to use setRecipients(Message.RecipientType type, Address[] addresses) as next:
message.setRecipients(
Message.RecipientType.TO,
new Address[]{new InternetAddress("abc#xyz.com"), new InternetAddress("def#xyz.com")}
);
My team and I coded a mail component to be used by other teams in our application. This component is designed to allow them to download emails using custom search conditions. The one that is being used at the moment is a mail search between a range of dates from Gmail accounts using IMAP protocol. It was working properly until April 4th 2016 6:00AM GMT+1, only downloading email within the range. However, since 8:00AM GMT+1, the response from the server suddenly changed and it started returning the whole INBOX folder!
Repeating the initial tests, we discovered that we were receiving the whole INBOX folder instead of those within the range. After some research down to the IMAP request, it seemed that Gmail changed the amount of emails returned under certain conditions:
When the "start date" SearchTerm had a ComparisonTerm.GT term, or
When the "end date" SearchTerm had a ComparisonTerm.LE term
In both cases, Gmail's IMAP server returns all the emails in the folder. On the contrary, as an example, Yahoo's IMAP server just returns those emails which match the given condition.
We opened a ticket to them, asking if there was any change in their response, but they answered that they did not change anything. Of course, there is no way to prove it (we still don't have the time machine).
As we had a great impact with this unexpected behaviour, we decided to investigate further, and we created a simple mail client to download mail using different condition combinations from different IMAP servers.
Starting from this link's program, we added the functionality to check with other, but changing the library to meet our javax.mail version 1.5.5. Therefore, we avoid different implementation behaviours.
The code is attached below:
package gmail;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.AndTerm;
import javax.mail.search.ComparisonTerm;
import javax.mail.search.ReceivedDateTerm;
import javax.mail.search.SearchTerm;
public class JavaMailTest {
public static void main(String[] args) {
JavaMailTest testClient=new JavaMailTest();
//Yahoo
//SEARCH SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
testClient.performTest(testClient.getYahooImapProps(),ComparisonTerm.GE,ComparisonTerm.LT);
//Gmail
//SEARCH SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
testClient.performTest(testClient.getGmailImapProps(),ComparisonTerm.GE,ComparisonTerm.LT);
//Yahoo
//SEARCH SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
testClient.performTest(testClient.getYahooImapProps(),ComparisonTerm.GE,ComparisonTerm.LE);
//Gmail
//SEARCH SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
testClient.performTest(testClient.getGmailImapProps(),ComparisonTerm.GE,ComparisonTerm.LE);
//Yahoo
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
testClient.performTest(testClient.getYahooImapProps(),ComparisonTerm.GT,ComparisonTerm.LT);
//Gmail
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
testClient.performTest(testClient.getGmailImapProps(),ComparisonTerm.GT,ComparisonTerm.LT);
//Yahoo
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
testClient.performTest(testClient.getYahooImapProps(),ComparisonTerm.GT,ComparisonTerm.LE);
//Gmail
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
testClient.performTest(testClient.getGmailImapProps(),ComparisonTerm.GT,ComparisonTerm.LE);
}
public int performTest(Properties props, int startTermCondition, int endTermCondition)
{
try {
Session session = Session.getDefaultInstance(props, null);
Message[] totalMessages = null;
Store store = session.getStore(props.getProperty("protocol"));
store.connect(props.getProperty("mail.imap.host"), props.getProperty("account"), props.getProperty("pass"));
Folder inbox = store.getFolder("inbox");
inbox.open(Folder.READ_ONLY);
SimpleDateFormat ft = new SimpleDateFormat ("yyyy-MM-dd");
Date startDate = ft.parse("2016-04-03");
Date endDate = ft.parse("2016-04-07");
System.out.println("Testing email account: <"+props.getProperty("account")+"> with startDate: <" + startDate + "> (ComparisonTerm."+
getConditionText(startTermCondition)+") and endDate: <" + endDate+"> (ComparisonTerm."+getConditionText(endTermCondition)+")");
Message[] messages = inbox.getMessages();
if (messages != null && messages.length > 0) {
SearchTerm startDateTearm =
new ReceivedDateTerm(startTermCondition, startDate);
SearchTerm endDateTerm =
new ReceivedDateTerm(endTermCondition, endDate);
SearchTerm andTerm = new AndTerm(startDateTearm, endDateTerm);
totalMessages = inbox.search(andTerm);
if(totalMessages.length > 0){
System.out.println("Found "+totalMessages.length+" matching messages (Total messages in folder: "+messages.length+")");
}
/*for (int i = 0; i < totalMessages.length; i++) {
System.out.println(totalMessages[i].getReceivedDate() + " --> Mail Subject:- " + totalMessages[i].getSubject());
}*/
//First message
int currentMessage=0;
System.out.println("First Message: "+totalMessages[currentMessage].getReceivedDate() + " --> Mail Subject: " + totalMessages[currentMessage].getSubject().substring(0, 5));
//Last message
currentMessage=totalMessages.length-1;
System.out.println("Last Message: "+totalMessages[currentMessage].getReceivedDate() + " --> Mail Subject: " + totalMessages[currentMessage].getSubject().substring(0, 5));
}
inbox.close(true);
store.close();
return totalMessages.length;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public static String getConditionText(int condition)
{
String returnValue="";
switch (condition) {
case ComparisonTerm.EQ:
returnValue="EQ";
break;
case ComparisonTerm.GE:
returnValue="GE";
break;
case ComparisonTerm.GT:
returnValue="GT";
break;
case ComparisonTerm.LE:
returnValue="LE";
break;
case ComparisonTerm.LT:
returnValue="LT";
break;
case ComparisonTerm.NE:
returnValue="NE";
break;
default:
returnValue="Error";
break;
}
return returnValue;
}
public Properties getYahooImapProps()
{
Properties props = new Properties();
//Yahoo
String imapServer="imap.mail.yahoo.com";
String imapPort="993";
String account="********#yahoo.es";
String pass="*********";
props.setProperty("mail.imap.host", imapServer);
props.setProperty("mail.imap.port", imapPort);
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.auth", "true");
props.setProperty("account", account);
props.setProperty("pass", pass);
props.setProperty("protocol", "imaps");
return props;
}
public Properties getGmailImapProps()
{
Properties props = new Properties();
//Gmail
String imapServer="imap.gmail.com";
String imapPort="143";
String account="******#gmail.com";
String pass="********";
props.setProperty("mail.imap.host", imapServer);
props.setProperty("mail.imap.port", imapPort);
/*props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.auth", "true");*/
props.setProperty("account", account);
props.setProperty("pass", pass);
props.setProperty("protocol", "imap");
return props;
}
}
To make the program output clearer, I added the request right before the first method output:
//SEARCH SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
Testing email account: <*********#yahoo.es> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GE) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LT)
Found 5 matching messages (Total messages in folder: 78)
First Message: Mon Apr 04 23:14:22 CEST 2016 --> Mail Subject: Aviso
Last Message: Tue Apr 05 00:48:00 CEST 2016 --> Mail Subject: Alter
//SEARCH SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
Testing email account: <*********#gmail.com> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GE) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LT)
Found 92 matching messages (Total messages in folder: 20138)
First Message: Sun Apr 03 04:08:47 CEST 2016 --> Mail Subject: Tu es
Last Message: Wed Apr 06 22:12:45 CEST 2016 --> Mail Subject: ¿Quie
//SEARCH SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
Testing email account: <*********#yahoo.es> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GE) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LE)
Found 5 matching messages (Total messages in folder: 78)
First Message: Mon Apr 04 23:14:22 CEST 2016 --> Mail Subject: Aviso
Last Message: Tue Apr 05 00:48:00 CEST 2016 --> Mail Subject: Alter
//SEARCH SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
Testing email account: <*********#gmail.com> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GE) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LE)
Found 20138 matching messages (Total messages in folder: 20138)
First Message: Sat Sep 04 13:23:35 CEST 2004 --> Mail Subject: Gmail
Last Message: Tue Apr 19 10:09:06 CEST 2016 --> Mail Subject: El re
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
Testing email account: <*********#yahoo.es> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GT) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LT)
Found 5 matching messages (Total messages in folder: 78)
First Message: Mon Apr 04 23:14:22 CEST 2016 --> Mail Subject: Aviso
Last Message: Tue Apr 05 00:48:00 CEST 2016 --> Mail Subject: Alter
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 BEFORE 7-Apr-2016 ALL
Testing email account: <*********#gmail.com> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GT) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LT)
Found 20138 matching messages (Total messages in folder: 20138)
First Message: Sat Sep 04 13:23:35 CEST 2004 --> Mail Subject: Gmail
Last Message: Tue Apr 19 10:09:06 CEST 2016 --> Mail Subject: El re
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
Testing email account: <*********#yahoo.es> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GT) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LE)
Found 5 matching messages (Total messages in folder: 78)
First Message: Mon Apr 04 23:14:22 CEST 2016 --> Mail Subject: Aviso
Last Message: Tue Apr 05 00:48:00 CEST 2016 --> Mail Subject: Alter
//SEARCH NOT ON 3-Apr-2016 SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
Testing email account: <*********#gmail.com> with startDate: <Sun Apr 03 00:00:00 CEST 2016> (ComparisonTerm.GT) and endDate: <Thu Apr 07 00:00:00 CEST 2016> (ComparisonTerm.LE)
Found 20138 matching messages (Total messages in folder: 20138)
First Message: Sat Sep 04 13:23:35 CEST 2004 --> Mail Subject: Gmail
Last Message: Tue Apr 19 10:09:06 CEST 2016 --> Mail Subject: El re
From this result we can say the following:
Yahoo returns the proper amount of emails, considering the given Java conditions.
Javamail's request is probably too ambiguous.
#Gmail: given the bunch of conditions in some requests... why you just decide to return the whole folder?
Why is there a different response for the same request?
Who is returning mails right?
Aren't protocols designed to standarise things instead of making it even worse?
We also tried with an Outlook account, with the same result as Gmail.
It sure looks like a bug in Gmail to me. I was able to reproduce it myself. I'm really surprised if Outlook.com has the same bug.
Why do you think the request is ambiguous? The IMAP spec is pretty clear.
A few notes...
Are you sure you're using JavaMail 1.5.5? The SEARCH commands you're showing reflect a JavaMail bug from before 1.5.3.
You should change Session.getDefaultInstance to Session.getInstance.
You don't need the socket factory properties; just set "mail.imap.ssl" to "true" instead.
#BillShannon
I think #popilla20k sees the request ambiguous because when he makes a request with a "GT" AND "LE" searchTerm (andTerm), it is decomposed, for example, as:
//SEARCH SINCE 3-Apr-2016 OR BEFORE 7-Apr-2016 ON 7-Apr-2016 ALL
I must say I've seen a change in Google's behaviour on April 6. Days before, I retrieved all mails that satisfied the condition with "GT" AND "LE" searchTerm. After April 6, I see the same behaviour showed by #popilla20k (using javamail 1.5.5)
Even so, I think the clause OR BEFORE invalids the first one. Does it should be AND clause, isn't? Anyway, days before April 6 the same requests were answered differently than nowadays.
Thanks.
I am experiencing weird problems over IMAP in JavaMail.
I already know alot in terms of JavaMail and I also know where to look for Questions/Answers, yet I cannot find a solution for this issue.
I have IMAP channel, on which I can set SSL enabled or disabled.
When I create new email message (let's say, Subject: "TEST", Body: "HELLO") and send it from Thunderbird client, to be able to download it with my IMAP channel, things are getting weird.
On SSL ENABLED, everything works fine. (in my IMAP channel) I get message from email folder, after successfuly connecting to the store, then i getContent() from this message (it is ALWAYS String type, not MimeMultipart or Multipart), and output is "HELLO".
However, on SSL DISABLED, everything also works fine, but I receive different body. It looks like whole message parsed (look below)
message.getContent().toString(); using SSL
HELLO
message.getContent().toString(); NOT using SSL
Return-Path: and#127.0.0.1
Received: from [127.0.0.1] (localhost [127.0.0.1]) by PC ; Wed, 22 Jan 2014 13:23:17 +0100
Message-ID: <52DFB835.9020300#127.0.0.1>
Date: Wed, 22 Jan 2014 13:23:17 +0100
From: "and#127.0.0.1" <and#127.0.0.1>
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130509 Thunderbird/17.0.6
MIME-Version: 1.0
To: and#127.0.0.1
Subject: TEST
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
Does anyone have any idea what's going on? Below are fragments of my code (to show you most important parts:
// properties used to create session
String protocol = useSSL ? "imaps" : imap";
properties.setProperty("mail.store.protocol", protocol);
properties.setProperty("mail." + protocol + ".host", ...);
properties.setProperty("mail." + protocol + ".user", ...);
properties.setProperty("mail." + protocol + ".port", ...);
properties.setProperty("mail." + protocol + ".password", ...);
// only when using ssl
properties.setProperty("mail.imaps.auth", "true");
properties.setProperty("mail.imaps.starttls.enable", "true");
properties.setProperty("mail.imaps.ssl.checkserveridentity", "true");
properties.setProperty("javax.net.ssl.trustStore", ...);
properties.setProperty("javax.net.ssl.trustStorePassword", ...);
// get store and other important things
Store store = this.session.getStore(protocol);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
Message[] newMessages = folder.getMessages();
for (Message newMessage : newMessages) {
Object o = newMessage.getContent();
System.out(o.toString()); // should write "HELLO", but instead it parses whole message (only on NON SSL MODE!)
}
// edit : added debug info
// edit 2 : debug info contains now full details with fetching folder, using { CONTENT_INFO, FLAGS, ENVELOPE }
DEBUG: getProvider() returning javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc]
DEBUG: mail.imap.fetchsize: 16384
DEBUG: protocolConnect returning false, host=127.0.0.1, user=and#127.0.0.1, password=<null>
* OK IMAPrev1
A0 CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 CHILDREN IDLE QUOTA SORT ACL NAMESPACE RIGHTS=texk
A0 OK CAPABILITY completed
DEBUG: protocolConnect login, host=127.0.0.1, user=and#127.0.0.1, password=<non-null>
A1 LOGIN and#127.0.0.1 password
A1 OK LOGIN completed
DEBUG: connection available -- size: 1
A2 SELECT INBOX
* 1 EXISTS
* 0 RECENT
* FLAGS (\Deleted \Seen \Draft \Answered \Flagged)
* OK [UIDVALIDITY 1378802425] current uidvalidity
* OK [UNSEEN 50167] unseen messages
* OK [UIDNEXT 50168] next uid
* OK [PERMANENTFLAGS (\Deleted \Seen \Draft \Answered \Flagged)] limited
A2 OK [READ-WRITE] SELECT completed
A3 SEARCH UNSEEN ALL
* SEARCH 1
A3 OK Search completed
A4 FETCH 1 (BODYSTRUCTURE)
* 1 FETCH (UID 50167 BODYSTRUCTURE ("TEXT" "PLAIN" ("CHARSET" "UTF-8") NIL "test" "7bit" 7 2))
A4 OK FETCH completed
A5 FETCH 1 (BODY[TEXT]<0.7>)
* 1 FETCH (UID 50167 ENVELOPE ("Tue, 28 Jan 2014 15:08:59 +0100" "test" (("and#127.0.0.1" NIL "and" "127.0.0.1")) (("and#127.0.0.1" NIL "and" "127.0.0.1")) (("and#127.0.0.1" NIL "and" "127.0.0.1")) (("and#127.0.0.1" NIL "and" "127.0.0.1")) NIL NIL NIL "<52E7B9FB.2030409#127.0.0.1>") BODY[HEADER] {479}
Return-Path: and#127.0.0.1
Received: from [127.0.0.1] (localhost [127.0.0.1]) by A-PC ; Tue, 28 Jan 2014 15:08:59 +0100
Message-ID: <52E7B9FB.2030409#127.0.0.1>
Date: Tue, 28 Jan 2014 15:08:59 +0100
From: "and#127.0.0.1" <and#127.0.0.1>
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130509 Thunderbird/17.0.6
MIME-Version: 1.0
To: and#127.0.0.1
Subject: test
Content-Type: text/plain; charset=UTF-8; format=flowed
Content-Transfer-Encoding: 7bit
BODY[TEXT]<0> {7}
HELLO
)
A5 OK FETCH completed
A6 FETCH 1 (FLAGS)
* 1 FETCH (UID 50167 FLAGS (\Seen))
A6 OK FETCH completed
A7 FETCH 1 (ENVELOPE INTERNALDATE RFC822.SIZE FLAGS BODYSTRUCTURE)
* 1 FETCH (UID 50167 RFC822.SIZE 462 FLAGS (\Seen) INTERNALDATE "28-Jan-2014 15:08:59 +0100" ENVELOPE ("Tue, 28 Jan 2014 15:08:59 +0100" "test" (("and#127.0.0.1" NIL "and" "127.0.0.1")) (("and#127.0.0.1" NIL "and" "127.0.0.1")) (("and#127.0.0.1" NIL "and" "127.0.0.1")) (("and#127.0.0.1" NIL "and" "127.0.0.1")) NIL NIL NIL "<52E7B9FB.2030409#127.0.0.1>") BODYSTRUCTURE ("TEXT" "PLAIN" ("CHARSET" "UTF-8") NIL "test" "7bit" 7 2))
A7 OK FETCH completed
A8 STORE 1 +FLAGS (\Seen)
* 1 FETCH (FLAGS (\Seen) UID 50167)
A8 OK STORE completed
A9 CLOSE
A9 OK CLOSE completed
DEBUG: added an Authenticated connection -- size: 1
IMAP DEBUG: IMAPProtocol noop
A10 NOOP
A10 OK NOOP completed
DEBUG: connection available -- size: 1
A11 SELECT INBOX
* 1 EXISTS
* 0 RECENT
* FLAGS (\Deleted \Seen \Draft \Answered \Flagged)
* OK [UIDVALIDITY 1378802425] current uidvalidity
* OK [UIDNEXT 50168] next uid
* OK [PERMANENTFLAGS (\Deleted \Seen \Draft \Answered \Flagged)] limited
A11 OK [READ-WRITE] SELECT completed
A12 SEARCH UNSEEN ALL
* SEARCH
A12 OK Search completed
A13 CLOSE
A13 OK CLOSE completed
DEBUG: added an Authenticated connection -- size: 1
IMAP DEBUG: IMAPProtocol noop
A14 NOOP
A14 OK NOOP completed
A15 LOGOUT
* BYE Have a nice day
A15 OK Logout completed
DEBUG: IMAPStore connection dead
DEBUG: IMAPStore cleanup, force false
DEBUG: IMAPStore cleanup done
server is hMailServer, running on 127.0.0.1 with SSL and NONSSL ports enabled.
It appears, that I get only headers from mail, but not the body..
Thanks for any suggestions, have a great day!
I fixed the problem. The bug I have encountered was linked to the "Unable to load BODYSTRUCTURE" error (links below - read about IMAP complexity).
https://java.net/projects/javamail/pages/Exchange
http://www.oracle.com/technetwork/java/javamail/faq/index.html#imapserverbug
All that had to be done, to get proper body message, was creating copy of the message, using MimeMessage constructor.
// newMessages - it is array of messages from the mail inbox
// create copy of the message using MimeMessage constructor
MimeMessage message = new MimeMessage(newMessages[0]); // without it, the content was as in my first post
// get content from the mssage
Object messageContent = message.getContent();
// output it as a string
System.out.println(messageContent.toString());
The problem is solved, now I receive what I want and what I should. The only thing left is, why there was a difference between SSL and NONSSL message content? Maybe antivirus problem?
Thanks for help and interest.
Have a great day.
I tried until now to create an object of type MimeMessage using JavaMail api, and after that to obtain its raw representation, but with no success. The only thing that I could obtain is a raw representation of the content of the email, but the header, subject, or recipients were not included. I am interested in any suggestions, any java libraries, that could help me in creating an email object, and after that obtain its raw representation. The raw representation should look something like this:
received: from imta14.emeryville.ca.mail.myisp.net ([nn.nn.30.46])
by alnrmxc19.isp.net (alnrmxc19) with ESMTP
id <20080930215116a19007q9u6e>; Tue, 30 Sep 2008 21:51:16 +0000
X-Originating-IP: [nn.nn.30.46]
Received: from libertatea.go ([nn.nn.161.160])
by IMTA14.mail.isp.net with isp
id M9qy1a00V3TwUto0E9rELB; Tue, 30 Sep 2008 21:51:15 +0000
X-Authority-Analysis: v=1.0 c=1 a=DZlucjOqAY8A:10 a=mnGO974OAAAA:8
a=9MJFf195B83LjESASTQA:9 a=Lm7NQ261g8eJHgoaELoA:7
a=7Narey355jFQWZRww2lj1r9-lCkA:4 a=8COHQAuY8ZYA:10 a=zEVpGHA-kecA:10
a=37WNUvjkh6kA:10
Received: by libertatea.go id hm1nfa0di0sn for <xxx#myisp.net>; Sun,30 Sep 2018 09:36:35
+0300 (envelope-from <Hometown.Quotes_ary#mousemegadot.com>)
Message-ID: <79864795#mousemegadot.com>
Date: Sun, 30 Sep 2018 09:36:35 +0300
From: "Hometown Quotes" <Hometown.Quotes_ary#mousemegadot.com>
To: dummy#myisp.net
Subject: Find Affordable Auto Insurance Today
MIME-Version: 1.0
X-UID: 79864795.modhnrfo.jhhnk.1
Content-Type: multipart/alternative; boundary="0-1411506895-1200484069=:66653"
Content-Transfer-Encoding: 8bit
X-PMFLAGS: 570966272 9 1 PE71PYHD.CNM
X-UC-Weight: [# ] 51
X-CC-Diagnostic: Test 'LazyHTML Tolerant' (51)
--0-1411506895-1200484069=:66653
Content-Type: text/plain; charset=iso-8859-1
Content-Transfer-Encoding: 8bit
--0-1411506895-1200484069=:66653
Content-transfer-encoding: 8bit
Content-Type: text/html; charset=iso-8859-1; DelSp="Yes"; format="flowed"
What you are looking for is MimeMessag#writeTo which outputs the message as an RFC 822 format stream.
An example of using writeTo to convert a MimeMessage to a String.
MimeMessage mimeMessage;
// mimeMessage get assigned
ByteArrayOutputStream output = new ByteArrayOutputStream();
mimeMessage.writeTo(output);
String rawEmail = output.toString();