当我使用电子邮件服务实现时,我使用了一个很酷的提示。因此,如果您也使用,并且只想检查消息是否按预期格式,检查附件是否存在,HTML格式是否正确,图像是否正确引用等等,则可以构建整个消息,并且在调试期间,您可以拥有一些这样的代码:MimeMessage
MimeMessage msg = new MimeMessage(session);
...
if ("1".equals(System.getProperty("mail.debug"))) {
msg.writeTo(new FileOutputStream(new File("/tmp/sentEmail.eml")));
}
每次执行此操作时,instane 都会保存到 。您可以使用电子邮件阅读器打开此文件,并检查一切是否正常。MimeMessage
emailSent.eml
当然,您需要使用 -Dmail.debug=1 参数执行应用程序。
使用此方法的附加文件,文本消息和html消息的示例可能如下所示:
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("<h1>test message and so on in HTML</h1>", "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")));
}
}
}