需求:只发送文本邮件(带图片和附件的未测试)
库版本:javamail-1.4.7
导入Java工程中jar包:mailapi.jar + smtp.jar
代码如下:
package com.buyu.mail; import java.util.Properties; 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 Mail { /** * 发送邮件 */ public static boolean send(String smtp, String from, String to, String subject, String content, String username, String password) { try { // 1.设置SMTP主机 Properties props = System.getProperties(); props.put("mail.smtp.host", smtp); props.put("mail.smtp.auth", "true"); // 2.创建MIME邮件对象 Session session = Session.getDefaultInstance(props, null); // 获得邮件会话对象 MimeMessage mimeMsg = new MimeMessage(session); // 创建MIME邮件对象 Multipart mp = new MimeMultipart(); // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 // 5.设置邮件主题 mimeMsg.setSubject(subject); // 6.设置邮件正文 BodyPart bp = new MimeBodyPart(); bp.setContent("" + content, "text/html;charset=GBK"); mp.addBodyPart(bp); // 7.设置发件人和收件人 mimeMsg.setFrom(new InternetAddress(from)); mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // 8.开始发送邮件 mimeMsg.setContent(mp); Transport transport = session.getTransport("smtp"); transport.connect((String) props.get("mail.smtp.host"), username, password); transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); transport.close(); System.out.println("发送邮件成功!"); } catch (Exception e) { System.err.println("邮件发送失败!"); return false; } return true; } }
String smtp = "smtp.163.com"; String from = "[email protected]"; String to = "[email protected]"; String subject = "主题xxx"; String content = "内容xxx"; String username = "[email protected]"; String password = "密码xxx"; Mail.send(smtp, from, to, subject, content, username, password);