日期:2014-05-20 浏览次数:20888 次
import java.util.Properties; import javax.mail.Address; import javax.mail.Message; 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; public class SendTest { /* * * stmp信息 * */ private static String smtp="smtp.gmail.com"; private static String user="lhjtianji"; private static String password="********"; private static String from="lhjtianji@gmail.com"; //邮件发送 public static void sendemail(String[] to,String subject,String body){ Properties props=new Properties(); //获得邮件服务器,用户名,密码等信息 props.put("mail.smtp.host", "127.0.0.1"); props.put("mail.smtp.auth", "true"); //需要smtp验证 Session ssn=Session.getInstance(props,null); System.out.println("发送成功1"); if(smtp.indexOf("smtp.gmail.com")>=0)//google smtp验证 { props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); } MimeMessage message=new MimeMessage(ssn); System.out.println("发送成功2"); try { InternetAddress fromAddress=new InternetAddress(from); //发件人的地址 try { message.setFrom(fromAddress); //收件人地址 //单个接受者 if(to.length<2){ Address toAddress=new InternetAddress(to[0]); message.addRecipient(Message.RecipientType.TO, toAddress); //收件人地址的类型 System.out.println("接受者的地址:"+toAddress); } if(to.length>=2){ Address[] toAddress=new Address[to.length]; for(int i=0;i<to.length;i++){ InternetAddress toer=new InternetAddress(to[i]); toAddress[i]=toer; System.out.println("接受者的地址:"+toer); } message.addRecipients(Message.RecipientType.TO, toAddress); } message.setSubject(subject); message.setContent(body, "text/html;charset=GBK"); message.setText(body); System.out.println("发送成功3"); Transport transport=ssn.getTransport("smtp"); System.out.println("发送成功4"); transport.connect(smtp, user, password); System.out.println("发送成功5"); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); System.out.println("发送成功6"); //Transport.send(message); System.out.println("发送成功7"); transport.close(); System.out.println("发送成功8"); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args){ /* String [] to={"4138960@163.com"}; String subject="hello"; String str="test"; SendTest test=new SendTest(); test.sendemail(to, subject, str); System.out.println("ok");*/ } }