在 WebSphere Studio 中使用 JavaMail
2009-11-08 00:00:00 来源:WEB开发网选择 Web =>Servlet,然后单击 Next。
输入 com.ibm.javamailsample作为 Package name。
输入 TestServlet作为 Servlet name。然后单击 Finish。
将黑体子代码添加到编辑器中。将发送者和接收者的电子邮件改为您自己的。例如,将 youremail@email.com 改为您自己的电子邮件地址。保存它。
package com.ibm.javamailsample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @version 1.0
* @author
*/
public class TestServlet extends HttpServlet {
/**
* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}
/**
* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}
public void performTask(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
PrintWriter out = resp.getWriter();
out.println("hello");
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
javax.mail.Session mail_session =
(javax.mail.Session) ctx.lookup(
"java:comp/env/mail/session1");
MimeMessage msg = new MimeMessage(mail_session);
msg.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse("youremail@email.com"));
msg.setFrom(new InternetAddress("jcyfung@ca.ibm.com"));
msg.setSubject("testing");
msg.setText("hello - testing");
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
更多精彩
赞助商链接