我需要从Tomcat中运行的servlet发送电子邮件。我将始终将相同主题但内容不同的邮件发送给同一收件人。
用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,\n\nHow are you?"); // Send the message. Transport.send(msg); } catch (MessagingException e) { // Error. }
您可以在此处从Sun获得JavaMail库:http : //java.sun.com/products/javamail/