Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
558 views
in Technique[技术] by (71.8m points)

email - How do I send an e-mail in Java?

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.

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

Related:

How do you send email from a Java app using GMail?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's my code for doing that:

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 = "[email protected]";
String from = "[email protected]";
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.
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...