前几个星期,我发表了有关commons-email的简易发送的案例,之前的案例只是在main方法中成功是实现发送邮件功能。
这次,我参考了一下javamail 发送邮件的原理,成功搞定,commons-email在web端邮件发送的成功。之后查找相关资料后发现,commons-email是基于javamail所开发的。
下面就是成功过的案例:
第一步导入相关jar包,这里我就不多说了,在之前发表的文章中有。
第二步,创建web工程,创建CommonsEmail.java(这里是servlet,名字自己定)
import java.io.IOException;
import java.util.Date;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import com.sun.mail.smtp.SMTPSSLTransport;
public class CommonsEmail extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Email email = new SimpleEmail();
email.setHostName("smtp.qq.com");
email.setAuthentication("********@QQ.com", "**********");
email.setSslSmtpPort("465");
try {
Session session = email.getMailSession();
MimeMessage message = new MimeMessage(session);
InternetAddress from = new InternetAddress("********@qq.com");
message.setFrom(from);
InternetAddress to = new InternetAddress("*********@qq.com");
message.setRecipient(RecipientType.TO, to);
message.setSubject("commons-email Test!!");
message.setSentDate(new Date());
message.setContent("commons-email,邮箱测试", "text/html;charset=UTF-8");
Transport transport = new SMTPSSLTransport(session, null);
transport.connect("smtp.qq.com","**********@QQ.com","egktkcfylbdxbddh");
transport.sendMessage(message, message.getAllRecipients());
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这里我就不再注释了,因为之前我发表的有关javamail和简易的commons-emai案例中都有相关注释。想知道相关注释,可以去观看相关文章。