how to convert String to message in java mail api? - java

how to convert String to message in java mail api?

You can use the MimeMessage constructor which accepts an InputStream. (See the JavaMail documentation)
Message msg = new MimeMessage(mySession,
new ByteArrayInputStream(myString.getBytes()));

I'm not sure what you're after. Perhaps The Quintessential Program to Send E-Mail [J2EE] helps?
Key method being msg.setText(content).

If the String contains the message body, just take or create a Message object (like a MimeMessage) and use the setTextmethod.
Otherwise, if the String holds a 'full' email, you'll have to separate header and body (from the String) and could use the addHeaderLine() method to recreate a message header.

Related

How correctly parse SES bounced JSON SNS Notification in Java

I am receiving JSON from SNS topic, which I believe is not correct
{
"Type":"Notification",
"MessageId":"message-id-is-this",
"TopicArn":"bouncer.topic.name.here",
"Message":"{\"notificationType\":\"Bounce\",\"bounce\":{\"bounceType\":\"Permanent\",\"bounceSubType\":\"General\",\"bouncedRecipients\":[{\"emailAddress\":\"bounce#simulator.amazonses.com\",\"action\":\"failed\",\"status\":\"5.1.1\",\"diagnosticCode\":\"smtp; 550 5.1.1 user unknown\"}],\"timestamp\":\"2017-04-24T12:58:05.716Z\",\"feedbackId\":\"feedback.id.is.here\",\"remoteMtaIp\":\"192.168.10.1\",\"reportingMTA\":\"dsn; smtp.link.here\"},\"mail\":{\"timestamp\":\"2017-04-24T12:58:05.000Z\",\"source\":\"senderEmail#domainname.com\",\"sourceArn\":\"arn:aws:ses:us-east-1:someid:identity/some#domain.org\",\"sourceIp\":\"127.0.0.1\",\"sendingAccountId\":\"sending.account.id.is.this\",\"messageId\":\"message-id-is-this\",\"destination\":[\"bounce#simulator.amazonses.com\"]}}",
"Timestamp":"2017-04-24T12:58:05.757Z",
"SignatureVersion":"1",
"Signature":"signature.link",
"SigningCertURL":"certificate.link.here",
"UnsubscribeURL":"un.subscribe.link"
}
The problem is with "Message" attribute which instead of holding an object, is referring to string of an object
contains
"Message":"{\"key\":\"value\"}"
instead of
"Message":{"key":"value"}"
hence not mapped to Message class
Temporarily I solved this problem by receiving into string variable and then convert it
private String Message;
private Message objMessage;
and then
Notification noti = toObject(jsonString, Notification.class);
Message msg = toObject(noti.getMessage(), Message.class);
noti.setObjMessage(msg);
for transformation, I am using ObjectMapper.readValue(...)
What is the correct way to solve this problem?
This format is correct.
There are two independent services in the loop, SES and SNS.
The outer structure is an SNS notification -- a generic structure that SNS uses do deliver anything that SNS delivers.
It contains a Message attribute, whose value is always a string, since that is what kind of messages SNS delivers -- strings. Not objects. SNS has no sense of the Message attribute's value being any kind of object. It could be anything, as long as it's valid UTF-8, SNS doesn't care.
To deliver an object as a string, it has to be serialized... and the inner serialization happens to also be JSON.
So Message is nested JSON-in-JSON.
And that's what it's supposed to look like.
When the outer object is serialized, the reserved JSON characters inside must be escaped, as shown here. After the first deserialization, you have exactly what SES sent you -- a JSON string.
You then need to deserialize the resulting string in order to get your object.
I don't think you're doing it wrong. If you are, then I've been doing it wrong for years.

How to get the Jgroups Message object content as string

I'm using jgroups for cluster node communication. I'm sending messages using channel, but unable to get the received message content. Used msg.getBuffer() and msg.getRawBuffer() methods, but after converting into string getting SOH SOH in the outpout. I just want only the message content not the 'src' or 'dest' hosts. How to get that from Message object?
If you use a string as payload, I suggest either
Set the contents using msg.setObject("hello world") and msg.getObject(), which returns the string "hello world"
OR
Set the contents using msg.setBuffer("hello world".getBytes()) and new String(msg.getRawBuffer(), msg.getOffset(), msg.getLength()).
In the first case, you use a helper method of JGroups to set and retrieve the object, in the latter case you do the (de-)serialization yourself.

add footer/signature to mail in Java

In one of my Java applications I have to forward e-mails. So, I get e-mails (plain text or multipart) with any content (maybe also attachments). I edit their subject, from- and to-header and send them via SMTP.
I already implemented this using Apache James Mime4j and Apache Commons Net but now I also have to append a footer/signature to the content of each e-mail.
Can I achieve this with Mime4j too? Would be great! How? If not: is there another way?
EDIT: Details after Wolfgang Fahl's comment:
Maybe I'm using the library the wrong way, but I am parsing the message as follows:
MessageBuilder messageBuilder = new DefaultMessageBuilder();
InputStream in = ...
Message m = messageBuilder.parseMessage(in);
Now I have an instance of Message and I can set it's subject, sender, etc. But Message does not provide a method setText() or something like that. Ok, there is getBody() but then I don't know how to manipulate the Body.

Is it possible to build Apache HtmlEmail from string representation?

I'm building a ImageHtmlEmail in order to download and embed all the images from given HTML into a multipart email. I need to store that email for sending later.
Problem is, I can get the resulting email text and content-type, but I see no means to construct an ImageHtmlEmail back from a text and a content-type. Is it possible at all? Or should I go with raw javax.mail for actual sending?
I was able to create javax.mail.internet.MimeMessage out of String representation of an email (ASCII dump as one one get on downloading original email from gmail). However not been very successful in constructing Email subclasses like HtmlEmail from it yet.
MimeMessage mimeMessage = MimeMessageUtils.createMimeMessage(Session.getDefaultInstance(new Properties()), new ByteArrayInputStream(oneEmail.toString().getBytes()));
It does give me most of the things I can think of as useful using its getter methods.
Not sure what you mean with "building HtmlEmail from string", but constructing an ImageHtmlMail should be fairly easy, see the sample at http://commons.apache.org/email/userguide.html, all you need to provide is some html-text via setHtmlMsg()
import org.apache.commons.mail.HtmlEmail;
...
// load your HTML email template
String htmlEmailTemplate = ....
// define you base URL to resolve relative resource locations
URL url = new URL("http://www.apache.org");
// create the email message
HtmlEmail email = new ImageHtmlEmail();
email.setDataSourceResolver(new DataSourceResolverImpl(url));
email.setHostName("mail.myserver.com");
email.addTo("jdoe#somewhere.org", "John Doe");
email.setFrom("me#apache.org", "Me");
email.setSubject("Test email with inline image");
// set the html message
email.setHtmlMsg(htmlEmailTemplate);
// set the alternative message
email.setTextMsg("Your email client does not support HTML messages");
// send the email
email.send();

parse attachment from multipart mail content string in java

I'm testing an application sending a mail with attachment in a integration environment. For this i'm setting up a fake smtp mail server (http://quintanasoft.com/dumbster/) and configure my application to use it. At the end of my test i want to check if my application has sent the email via my fake mail server and also want to know, if the content (at least the attached file) is exactly that i'm expecting.
Dumpster is wrapping these mails into its own objects just containing header key-value pairs and the body as plain text. My question is how i can easily part the mail body to get and evaluate the attached file content from it.
Attach a file that you are certain of the mime-types in javamail. Sending the email over smtp allows us to make use of the fact that there is a string of data inside the body of the email before the bytes of the file. The bytes of the file are base64 and get included in the main chunk of the characters of the email.
private static final String YOUR_ATTACMETN_DATA = "Content-Type: image/jpeg; name=Invoice.jpgContent-Transfer-Encoding: base64Content-Disposition: attachment; filename=image.jpg";
#Before
public final void setup() throws UserException{
server = SimpleSmtpServer.start();
}
#After
public final void tearDown(){
server.stop();
}
#Test
public void test_that_attachment_has_been_recieved() throws IOException, MessagingException {
email = getMessage();
YourEmailSendingClass.sendEmail(email);
Iterator<SmtpMessage> it = server.getReceivedEmail();
SmtpMessage recievedMessage = (SmtpMessage)it.next();
assertTrue(recievedMessage.getBody.contains(YOUR_ATTACHMENT_DATA)));
}
Here is another is a page of someone who did something similar to this in greater detail.
http://www.lordofthejars.com/2012/04/why-does-rain-fall-from-above-why-do.html
As a place to start (not sure if there are easier ways to do it), consider using the JavaMail API. Try to grab the whole message (including headers) -- probably with SmtpMessage.toString(), wrap it in some new ByteArrayInputStream(smtpMessage.toString().getBytes()), and pass it to a javax.mail.internet.MimeMessage.
(NOTE: I'm not that familiar with the MIME standard and I don't know if you should use the getBytes(Charset) overload here).

Categories

Resources