如何使用Java发送电子邮件? [英] How do I send an e-mail in Java?

查看:125
本文介绍了如何使用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发送电子邮件的简单方法是什么? / p>

相关:



What's a simple, easy way to send an e-mail in Java?


如何使用GMail从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/

You can get the JavaMail libraries from Sun here: http://java.sun.com/products/javamail/

这篇关于如何使用Java发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆