JavaMail API提供了许多类, 可用于从Java发送电子邮件。 javax.mail和javax.mail.internet软件包包含发送和接收电子邮件所需的所有类。
为了更好地理解此示例, 请单击从Javamail API发送电子邮件的步骤
要使用JavaMail API发送电子邮件, 你需要加载两个jar文件:
- mail.jar
- activation.jar
下载这些jar文件或访问Oracle站点以下载最新版本。
通过Servlet中的JavaMail API发送电子邮件的示例
这是从servlet发送电子邮件的简单示例。对于此示例, 我们将创建3个文件:
- 用于输入的index.html文件
- SendMail.java, 一个servlet文件, 用于处理请求并向用户提供响应。它使用Mailer类的send方法发送电子邮件。
- Mailer.java, 这是一个Java类, 其中包含将电子邮件发送到所提到的收件人的send方法。
index.html
<form action="servlet/SendMail">
To:<input type="text" name="to"/><br/>
Subject:<input type="text" name="subject"><br/>
Text:<textarea rows="10" cols="70" name="msg"></textarea><br/>
<input type="submit" value="send"/>
</form>
SendMail.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SendMail extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String to=request.getParameter("to");
String subject=request.getParameter("subject");
String msg=request.getParameter("msg");
Mailer.send(to, subject, msg);
out.print("message has been sent successfully");
out.close();
}
}
Mailer.java
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mailer {
public static void send(String to, String subject, String msg){
final String user="sonoojaiswal@srcmini02.com";//change accordingly
final String pass="xxxxx";
//1st step) Get the session object
Properties props = new Properties();
props.put("mail.smtp.host", "mail.srcmini02.com");//change accordingly
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
});
//2nd step)compose message
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(msg);
//3rd step)send message
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
下载此示例(无IDE开发)
下载此示例(使用Eclipse IDE开发)
下载此示例(使用Netbeans IDE开发)
评论前必须登录!
注册