本文将通过简单的语言介绍烦琐的JAVAMAIL发Gmail邮件SSL使用方法(包括一个邮件发送例子)。与其他邮箱不同的是Gmail提供的POP3和SMTP是使用安全套接字层SSL的,因此常规的JavaMail程序是无法收发邮件的,下面是使用JavaMail发送Gmail邮件代码:
JavaMail包下载地址:http://java.sun.com/products/javamail/index.jsp JAF下载地址:http://java.sun.com/products/javabeans/jaf/
<%@ page contentType="text/html;charset=gb2312" %> <%@ page import=" javax.mail.*, javax.mail.internet.*, javax.activation.*,java.util.*" %> <%@ page import="java.security.Security.*"%> <html> <head> <TITLE>JSP meets JavaMail, what a sweet combo.</TITLE></HEAD> <BODY> <% try{ String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true");
//用户根据自己的需要填写相应的邮箱和登陆密码,下面的邮箱名称和密码不一定正确 String username = "kericai@gmail.com"; String password = "bigfish112";
Session sendMailSession; Store store; Transport transport; sendMailSession = Session.getInstance(props, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("kericai@gmail.com", "bigfish112"); }});
// -- Create a new message -- Message msg = new MimeMessage(sendMailSession);
// -- Set the FROM and TO fields -- msg.setFrom(new InternetAddress("kericai@gmail.com")); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("wangyou3705@sina.com.cn",false)); msg.setSubject("Hello"); msg.setText("How are you"); msg.setSentDate(new Date()); Transport.send(msg); System.out.println("Message sent.");
} catch(MessagingException m) { out.println(m.toString()); } %> </BODY> </HTML>
如各位测试上面的程序时出现什么错误可以联系我。并请各位多多指教。大鱼制作--QQ(120673406)
参考文章: http://www.knowsky.com/1455.html http://www.360doc.com/showWeb/0/0/41034.aspx
|