I\'m using javamail to send mails from my appengine application. It works perfectly in the deployment, but I can\'t figure out how to do this using the development server. Whene
When I worked with an e-mail service implementation I used a cool hint. So if you use MimeMessage
too, and want just check if the message is formatted as expected, checking if attachments are there, HTML is well formatted, images are right referenced and so on, you could build the entire message, and during debug you could have some code like this:
MimeMessage msg = new MimeMessage(session);
...
if ("1".equals(System.getProperty("mail.debug"))) {
msg.writeTo(new FileOutputStream(new File("/tmp/sentEmail.eml")));
}
Every time this is executed the MimeMessage
instane will be saved to emailSent.eml
. This file you can open with your e-mail reader and check if everything is fine.
Of course that you need to execute your application with -Dmail.debug=1 parameter.
An example with attached file, text message and html message with this approach could be like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.junit.Test;
public class MimeMessageTest {
@Test
public void tesstMimeMessage() throws MessagingException, FileNotFoundException, IOException {
Session session = Session.getDefaultInstance(new Properties(), null);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("admin@foo.bar", "Foo Admin"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("baz@foo.bar", "Baz User"));
msg.setSubject("Subject from admin e-mail to baz user");
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText("test message and so on");
mbp1.setContent("test message and so on in HTML
", "text/html");
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds = new FileDataSource("/tmp/fileToBeAttached");
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
if ("1".equals(System.getProperty("debug"))) {
msg.writeTo(new FileOutputStream(new File("/tmp/sentEmail.eml")));
}
}
}