以下是我的glassfish-resources.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<mail-resource debug="true"
enabled="true"
from="foo@bar.com"
host="smtp.mandrillapp.com"
jndi-name="java:app/mail/mySession"
object-type="user"
store-protocol="imap"
store-protocol-class="com.sun.mail.imap.IMAPStore"
transport-protocol="smtp"
transport-protocol-class="com.sun.mail.smtp.SMTPTransport"
user="foo@bar.com">
<description/>
<property name="mail.user" value="foo@bar.com"/>
<property name="mail.password" value="password"/>
<property name="mail.host" value="smtp.mandrillapp.com"/>
<property name="mail.port" value="587"/>
<property name="mail.smtp.socketFactory.port" value="587"/>
<property name="mail.smtp.socketFactory.fallback" value="false"/>
<property name="mail.smtp.auth" value="true"/>
<property name="mail.smtp.starttls.enable" value="true"/>
</mail-resource>
</resources>
发送电子邮件的方法:
public static void sendEmail(final Session session,
final String from,
final String to,
final String subject,
final String htmlPart,
final String txtPart)
throws AddressException,
MessagingException
{
MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(from));
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(RecipientType.TO, toAddress);
message.setSubject(subject);
// Create a multipart message consisting of a HTML body with an alternate plain text version.
MimeMultipart mp = new MimeMultipart("alternative");
// Plain text part.
MimeBodyPart textPlainPart = new MimeBodyPart();
textPlainPart.setContent(txtPart, "text/plain");
mp.addBodyPart(textPlainPart);
// HTML part.
MimeBodyPart textHtmlPart = new MimeBodyPart();
textHtmlPart.setContent(htmlPart, "text/html");
mp.addBodyPart(textHtmlPart);
// Put it all together.
message.setContent(mp);
message.saveChanges();
// Send the email.
Transport tr = session.getTransport("smtp");
String user = session.getProperty("mail.user");
String smtpPassword = session.getProperty("mail.password");
String smtpHost = session.getProperty("mail.host");
int port = Integer.parseInt(session.getProperty("mail.port"));
tr.connect(smtpHost, port, user, smtpPassword);
tr.sendMessage(message, new Address[] { toAddress });
tr.close();
}
当我调用上述方法时,似乎什么都没发生。它在不抛出异常的情况下到达了结尾,但我没有收到任何电子邮件。
显然,我已经配置错误,因为我已经能够使用电子邮件客户端通过Mandrill发送电子邮件。