1.需要的jar :mail.jar,activation.jar
2.QQ邮箱设置:设置 -帐户-开启服务:
3.注意点: 若用QQ邮箱,有发送次数限制的,发了一次后,就停了。建议用企业邮箱。
5.相关代码:服务器验证与处理代码
package com.jack.mail; import java.util.Properties; import javax.mail.Authenticator; 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 MailVConstructor { private Properties props = null; private Authenticator authenticator=null; private Session session = null; private MimeMessage message = null; public Properties createProperties(String host ){ Properties p = System.getProperties();; p.put("mail.smtp.localhost", "localhost"); p.put("mail.smtp.auth", "true");/*打开验证*/ p.put("mail.smtp.host", host); return p; } public Authenticator crateAuthenticator(String from ,String passWord){ Authenticator authenticator = new MailAuthenticator(from, passWord); return authenticator; } public Session createSession(Properties props,Authenticator authenticator){ Session session = Session.getDefaultInstance(props, authenticator); return session; } public MimeMessage createMessage(Session session){ MimeMessage message = new MimeMessage(session); return message; } /** * * @param host 发送邮件的服务器 * @param from 发送邮件的地址 ,如 :xxxxxxxx@qq.com * @param pwd 发送邮件的(用户)密码 ************* * @param to 接收邮件的地址 * @param subject 邮件的标题 * @param text 邮件的内容 */ public void sendMail(String host,String from,String pwd,String to,String subject,String text){ props= createProperties(host); authenticator = crateAuthenticator(from,pwd); session = createSession(props,authenticator); message = createMessage(session); try { message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject);/*邮件主题*/ message.setText(text);/*邮件内容*/ // 发送message Transport.send(message); System.out.println("已成功发送给 :"+to); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
package com.jack.mail; import javax.mail.Authenticator; import javax.mail.PasswordAuthentication; public class MailAuthenticator extends Authenticator { String authenName; // 用户名 String authenPass; // 密码 public MailAuthenticator(String authenName, String authenPass) { super(); this.authenName = authenName; this.authenPass = authenPass; } /* 若服务器需要身份认证,Sission会自动调用这个方法 */ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(authenName, authenPass); } }测试类
package com.jack.mail; public class TestMail { public static void main(String args[]) { String subject = "测试标题"; String text = "邮件内容"; MailVConstructor mc = new MailVConstructor(); mc.sendMail("smtp.exmail.qq.com", "jacklei2@baletu.com", "leixuan1225", "15618222119@qq.com", subject, text); } }结果:
原文地址:http://blog.csdn.net/laughing2me/article/details/34862723