如何使用 Java 发送电子邮件? [英] How do I send an e-mail in Java?
本文介绍了如何使用 Java 发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从 Tomcat 中运行的 servlet 发送电子邮件.我总是发送给同一个收件人,主题相同,但内容不同.
I need to send e-mails from a servlet running within Tomcat. I'll always send to the same recipient with the same subject, but with different contents.
用 Java 发送电子邮件的简单方法是什么?
What's a simple, easy way to send an e-mail in Java?
推荐答案
这是我的代码:
import javax.mail.*;
import javax.mail.internet.*;
// Set up the SMTP server.
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", "smtp.myisp.com");
Session session = Session.getDefaultInstance(props, null);
// Construct the message
String to = "you@you.com";
String from = "me@me.com";
String subject = "Hello";
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText("Hi,
How are you?");
// Send the message.
Transport.send(msg);
} catch (MessagingException e) {
// Error.
}
您可以从 Sun 此处获取 JavaMail 库:http://java.sun.com/products/javamail/
You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/
这篇关于如何使用 Java 发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文