javamail发送邮件

来源:互联网 发布:一手车主数据2016 编辑:程序博客网 时间:2024/06/06 12:57

import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Address;import javax.mail.BodyPart;import javax.mail.Message;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;public class JavaMail {private MimeMessage mimeMsg; // MIME邮件对象private Session session; // 邮件会话对象private Properties props; // 系统属性private boolean needAuth = false; // smtp是否需要认证private String username = "xxx@qq.com"; // smtp认证用户名和密码private String password = "xxx";private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象public JavaMail(String smtp) {setSmtpHost(smtp);createMimeMessage();}/** * @param hostName *            String */public void setSmtpHost(String hostName) {System.out.println("设置系统属性:mail.smtp.host = " + hostName);if (props == null)props = System.getProperties(); // 获得系统属性对象props.put("mail.smtp.host", hostName); // 设置SMTP主机}/** * @return boolean */public boolean createMimeMessage() {try {System.out.println("准备获取邮件会话对象!");session = Session.getDefaultInstance(props, null); // 获得邮件会话对象} catch (Exception e) {System.err.println("获取邮件会话对象时发生错误!" + e);return false;}System.out.println("准备创建MIME邮件对象!");try {mimeMsg = new MimeMessage(session); // 创建MIME邮件对象mp = new MimeMultipart();return true;} catch (Exception e) {System.err.println("创建MIME邮件对象失败!" + e);return false;}}/** * @param need *            boolean */public void setNeedAuth(boolean need) {System.out.println("设置smtp身份认证:mail.smtp.auth = " + need);if (props == null)props = System.getProperties();if (need) {props.put("mail.smtp.auth", "true");} else {props.put("mail.smtp.auth", "false");}}/** * @param name *            String * @param pass *            String */public void setNamePass(String name, String pass) {username = name;password = pass;}/** * 设置邮件的标题 */public boolean setSubject(String mailSubject) {System.out.println("正在设置邮件主题...");try {mimeMsg.setSubject(mailSubject);return true;} catch (Exception e) {System.err.println("设置邮件主题发生错误!");return false;}}/** * 设置信件内容 */public boolean setBody(String mailBody) {System.out.println("正在设置邮件内容...");try {BodyPart bp = new MimeBodyPart();bp.setContent("<font color='red'>【内容】</font>" + mailBody,"text/html;charset=GB2312");mp.addBodyPart(bp);return true;} catch (Exception e) {System.err.println("设置邮件正文时发生错误!" + e);return false;}}/** * 添加附件 */public boolean addFileAffix(String filename) {System.out.println("增加邮件附件:" + filename);try {BodyPart bp = new MimeBodyPart();FileDataSource fileds = new FileDataSource(filename);bp.setDataHandler(new DataHandler(fileds));bp.setFileName(fileds.getName());mp.addBodyPart(bp);return true;} catch (Exception e) {System.err.println("增加邮件附件:" + filename + "发生错误!" + e);return false;}}/** * 设置发信人 */public boolean setFrom(String from) {System.out.println("正在设置发信人...");try {mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人return true;} catch (Exception e) {return false;}}/** * 设置收信人 */public boolean setTo(String to) {System.out.println("正在设置收信人...");if (to == null)return false;try {mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));return true;} catch (Exception e) {return false;}}/** * @param name *            String * @param pass *            String */public boolean setCopyTo(String copyto) {if (copyto == null)return false;try {mimeMsg.setRecipients(Message.RecipientType.CC,(Address[]) InternetAddress.parse(copyto));return true;} catch (Exception e) {return false;}}/** *发送 */public boolean sendout() {try {mimeMsg.setContent(mp);mimeMsg.saveChanges();System.out.println("正在发送邮件....");Session mailSession = Session.getInstance(props, null);Transport transport = mailSession.getTransport("smtp");transport.connect((String) props.get("mail.smtp.host"), username,password);transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));System.out.println("发送邮件成功!");transport.close();return true;} catch (Exception e) {System.err.println("邮件发送失败!" + e);return false;}}/** * Just do it as this */public static void main(String[] args) {String mailbody = "你好!测试JavaMail!";JavaMail themail = new JavaMail("smtp.qq.com");themail.setNeedAuth(false);if (themail.setSubject("大坨美食团购") == false)return;if (themail.setBody(mailbody) == false)return;if (themail.setTo("xxx@qq.com,xxx@qq.com") == false)return;if (themail.setFrom("xxx@qq.com") == false)return;// if (themail.addFileAffix("d:\\test.jar") == false)// return;themail.setNamePass("邮箱", "密码");// 发送邮件的用户名和密码(即自己邮箱的用户名和密码,任何的邮箱,如163邮箱,smtp服务器地址为:smtp.163.com,用户名和密码是你的163注册的用户名和密码)if (themail.sendout() == false)return;}}


【可能报错及解决方案】

错误:java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream解决办法

主要原因:  

javax.mail和javax.activation这两个包已经在javaEE5当中属于基础包了,就是JDK中自带了已经,但是里面的方法与现在外面的mail.jar和activation.jar有一些出入,所以初学者在直接copy别人代码的时候往往会出现上面的错误。 
废话不多说下面是解决方法 
进到

D:\Program files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033\data\libraryset\EE_5

这个路径里,可以看到javaee.jar,用rar把这个文件打开,然后进到javax文件夹里,删除mail.jar和activation.jar(我的javaee.jar里,这两个东西是文件夹,总之删掉就OK,不过要注意备份一下)

删掉之后运行下面的代码,经行简单的修改以后就可以实现接收邮件的功能了


原创粉丝点击