我最近需要使用 IMAP 从 AppEngine 发送电子邮件,这对我有用。
我已经添加了这个库:
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/javax.mail-api -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.0-rc2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.mail/smtp -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>smtp</artifactId>
<version>1.6.0-rc2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.0-rc2</version>
</dependency>
这是代码:
package ro.cbn.it.call.utils;
import javax.activation.DataHandler;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import com.sun.mail.smtp.SMTPTransport;
import java.util.Properties;
public class MailUtils {
public static void sendEmail(String userId, String password, String messageBody, String fromEmail, String messageSubject, String messageToAddress) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "false");
Session session = Session.getInstance(props);
//session.setDebug(true);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
transport.connect("smtp.gmail.com", 587, userId, password);
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(messageBody.getBytes(), "text/plain"));
message.setSender(new InternetAddress(fromEmail));
message.setSubject(messageSubject);
message.setDataHandler(handler);
message.setRecipient(Message.RecipientType.TO, new InternetAddress(messageToAddress));
transport.sendMessage(message, message.getAllRecipients());
System.out.println("SentTo:"+messageToAddress);
}
}