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.
Related
I am triggering the AWS SNS through the API Gateway.
JSONObject requestBody = new JSONObject();
requestBody.put("phone_number", receiverNumber);
requestBody.put("sender_id", senderAlias);
requestBody.put("message_text", messageText);
This JSONObject is being sent to the api gateway as a ByteArrayInputStream throug the AWS SDK for Java v1.
There are "\n" in the text, to create line breaks. The sms however does not have a new line there, it just prints \n.
In the Api Gateway the message is extracted like this: method.request.body.message_text
How do I have to set up the messageText variable to print new lines in the SMS? I tried replacing it with \n or \\n or \\\\n.. Also tried ASCII, didn't work.
Invocation
As this is a quite complex programm I can't show all of it. It's triggered via Insomnia with a String in Json format like this:
It has to be a double backslahed n because thats just how the code needs it. The aws integration is an additional provider so it has to fit in already existing frames. The json object looks like this before being executed.
So I need to find a way to manipulate the string thats going in the object. But I don't know how.
EDIT 3:
Deleting previous edits, as they were not helpful and did not target the problem as I know now.
Finally closing down the issue. It's a problem in the API-Gateway. The object reaches the gateway just fine, with a \n. Which would work in the SNS Service. But to trigger the SNS Service, it's all going into one URL, which converts the \n into %5Cn
Before transformation:
URL:
So the problem is in the URL encoding..
Thanks to the AWS Support I now am able to send SMS with line breaks through the api gateway.
It was wrong to use URL Query Parameters. I removed all of them
I needed one HTTP Header:
Content-Type: 'application/x-www-form-urlencoded'
Then I used a Messaging Template like this, with passthrough: Never:
#set($message = $input.path('$.message_text'))
#set($phoneNumber = $input.path('$.phone_number'))
Action=Publish&PhoneNumber=$util.urlEncode($phoneNumber)&Message=$util.urlEncode($message)&MessageAttributes.entry.1.Name=AWS.SNS.SMS.SenderID&MessageAttributes.entry.1.Value.DataType=String&MessageAttributes.entry.1.Value.StringValue=Alias
Having my JSON Object in the Request like this:
{
"phone_number": "+4912345678",
"message_text": "Break\nHere",
"sender_id":"Alias"
}
Works perfectly fine with a line break in the SMS
I have some Java code which sends out an email with code somewhat like the following: Actually i got Mimemessage from Httprequest param and in that mimemessage i'm going to append some content to existing body.
If Mimemessage is of Multipart content-type , i'm not facing any issue while sending message.
If the message is of text/plain and text/html content-type, the content-transfer encoding which i set didn't applied to body.
Based on this docs
Q: Even though JavaMail does all the encoding and decoding for me, I need to manually control the encoding for some body parts. A: In the rare case that you need to control the encoding, there are several ways to override JavaMail's default behavior. A simple approach is as follows. After creating the entire message, call msg.saveChanges() and then use something like mbp.setHeader("Content-Transfer-Encoding", "base64") to force base64 encoding for the given body part.
Another approach is to subclass MimeBodyPart and override the updateHeaders method so that it first calls super.updateHeaders() and then sets the Content-Transfer-Encoding header as above.
Applied above also. But it doesn't works for me.
InputStream ins = request.getInputStream();
MimeMessage msg = new MimeMessage(session,ins);
msg.setContent("some non-Ascii content","text/plain; charset="UTF-8"");
//Tried setheader before saveChanges() method, also doesn't work for me
//msg.setHeader("Content-Transfer-Encoding","base64");
msg.saveChanges();
//Now tried based on above docs after saveChanges method, also doesn't work
msg.setHeader("Content-Transfer-Encoding","base64");
please help to solve this.
You duplicated most of this question in your other post, and I answered part of it there.
You would probably be better off sending the content for the mail message in the http request, then creating a new message on the server based on that content, instead of trying to send a complete MIME message to the server that you then edit.
I am a beginner of using Desktop.mail(URI) class, so I am looking for a way to add to, cc and subject to the mail when triggered from the program.
String mailTo = "test#domain.com";
String cc = "test2#domain.com";
String subject = "firstEmail";
String body = "the java message";
URI uriMailTo = new URI(mailTo,cc,subject,body);
Desktop desktop;
desktop = Desktop.getDesktop();
desktop.mail(uriMailTo);
can any one suggest any tutorials to learn this process, because I am looking for even more functions like receiving the data back from the outlook to the Java program.
Thanks in advance for help!
The Desktop.mail() function is a utility method for launching whatever mail program may exist in the users system (if any). You have (very) limited capability of controlling the actual mail message to be (eventually) sent, and once the mail client is displayed you're pretty much done - aka you wont be getting any feedback on what message was actually sent or wether it succeeded.
If you need this level of control then you should be using the JavaMail API, which does a lot of what you seem to need.
If you are stuck with using the Desktop mail client, then you might want to read up on RFC 2368. It describes all the fields that can be included in a mailto URI. So, you will be able to populate the message, but you won't get feedback on wether it was successfully sent or not:
mailto:joe#example.com?cc=bob#example.com&body=hello+world
A code example of constructing your URI (which is incorrect btw):
final String mailURIStr = String.format("mailto:%s?subject=%s&cc=%s&body=%s",
mailTo, subject, cc, body);
final URI mailURI = new URI(mailURIStr);
Where the substituted should be URL encoded if necessary.
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).
i want to create an intranet mailing system using java.so suggest me which API and what classes to use.
Without doubts use Apache Commons Email - it's an industry standard.
Commons Email aims to provide a API for sending email. It is built on top of the Java Mail API, which it aims to simplify.
Some of the mail classes that are provided are as follows:
SimpleEmail - This class is used to send basic text based emails.
MultiPartEmail - This class is used to send multipart messages. This allows a text message with attachments either inline or attached.
HtmlEmail - This class is used to send HTML formatted emails. It has all of the capabilities as MultiPartEmail allowing attachments to be easily added. It also supports embedded images.
EmailAttachment - This is a simple container class to allow for easy handling of attachments. It is for use with instances of MultiPartEmail and HtmlEmail.
Use the JavaMail API
Take a look at http://java.sun.com/products/javamail/
Try this library: http://github.com/masukomi/aspirin
It can actually send email (some kind of embedded MTA):
public class Main {
public static void main(String[] args) throws MessagingException {
MailQue que = new MailQue();
MimeMessage mes = SimpleMimeMessageGenerator.getNewMimeMessage();
mes.setText("test body");
mes.setSubject("test subject");
mes.setFrom(new InternetAddress("my#local.com"));
mes.setRecipients(Message.RecipientType.TO, "foo#bar.com");
que.queMail(mes);
}
}