java发邮件

         需要用到mail.jar这个包,地址http://www.oracle.com/technetwork/java/javamail-1-4-2-141075.html,网上有些资料说这个包依赖另一个包,叫什么JavaBeans Activation Framework (JAF)。我测试发现即使不用也行,不知道是不是版本问题,我用的版本1.4.2。发送速度很快,才一点运行,QQ邮箱马上就收到了。

 

Service

package mainCenter; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * Created by IntelliJ IDEA. * User: wnj * Date: 2011-1-26 * Time: 18:53:32 * To change this template use File | Settings | File Templates. */ public class MailService { private static final String smtpServer = "mail.meituan.com";//发件服务器 //private static final String smtpServer = "smtp.gmail.com";//发件服务器 private static final String account = "[email protected]";//发件用户名 private static final String pwd = "1234";//发件密码 public static int sendMail(String address, String subject, String content) { //int rs = -1; Properties props = System.getProperties(); // Setup mail server //props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); //props.setProperty("mail.smtp.port", "25"); //props.setProperty("mail.smtp.socketFactory.port", "25"); //props.setProperty("mail.smtp.port", "465"); //props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.host", smtpServer); // Get session props.put("mail.smtp.auth", "true"); //这样才能通过验证 MyAuthenticator myauth = new MyAuthenticator(account, pwd); Session session = Session.getDefaultInstance(props, myauth); // session.setDebug(true); try{ // Define message MimeMessage message = new MimeMessage(session); // Set the from address message.setFrom(new InternetAddress(account)); // Set the to address message.addRecipient(Message.RecipientType.TO, new InternetAddress(address)); // Set the subject message.setSubject(subject); // Set the content //message.setText(content); message.setContent(new String(content.getBytes(), "iso-8859-1"), "text/html"); message.saveChanges(); Transport.send(message); }catch(Exception e){ e.printStackTrace(); return -1; } return 1; } } //校验发信人权限的方法 // package com.hyq.test; // // import javax.mail.PasswordAuthentication; class MyAuthenticator extends Authenticator { private String strUser; private String strPwd; public MyAuthenticator(String user, String password) { this.strUser = user; this.strPwd = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(strUser, strPwd); } }

 

main函数

public static void main(String[] args){ MailService.sendMail("[email protected]", "test", "ok"); }

 

不同的邮箱可能设置不一样,谷歌邮箱就得把我的一些注释去掉替换原来代码。不管怎么说,我用上面代码发成功了谷歌的和公司自己架设的邮箱系统。

你可能感兴趣的:(java,exception,properties,String,session,javabeans)