今天做公司的项目,需要用到邮件发送,由于以前没有这方面的经验,遇到了不少问题,最终还是依靠google将问题解决。但是担心不久就忘掉,还是记下来为好。
import java.util.Properties; 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; /** * 邮件服务 * * @author shelltea * */ public class MailService { private static final String HOST = "smtp.gmail.com"; private static final String USER_NAME = ""; private static final String PASSWORD = ""; private static final String FROM = "[email protected]"; private String to; private String subject; private String content; /** * 构造方法 * * @param to * 收件人邮箱 */ public MailService(String to) { this.to = to; } /** * 发送邮件,在调用此方法之前,请设置邮件模式 * * @throws AddressException * @throws MessagingException */ public void send() throws AddressException, MessagingException { Properties props = new Properties(); props.put("mail.smtp.host", HOST);// 指定SMTP服务器 props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证 props.put( "mail.smtp.starttls.enable" , "true" ); Session mailSession = Session.getDefaultInstance(props); Message message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(FROM));// 发件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// 收件人 message.setSubject(subject);// 邮件主题 message.setText(content);// 邮件内容 message.saveChanges(); Transport transport = mailSession.getTransport("smtp"); transport.connect(HOST, USER_NAME, PASSWORD); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } /** * 设置邮件为发送帐户和密码模式 * * @param name * @param password */ public void nameAndPasswordMode(String name, String password) { this.subject = ""; this.content = "尊敬的客户:您好!您的账号为:" + name + ",密码为:" + password + "。请妥善保存,并及时更改。"; } }
下面是测试代码:
import javax.mail.MessagingException; import javax.mail.internet.AddressException; import org.junit.Test; public class MailServiceTest { @Test public void testSendMail() { MailService mailService = new MailService("[email protected]"); mailService.nameAndPasswordMode("dasdasd", "123345567"); try { mailService.send(); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } } }
执行下就出现了下面的异常:
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
gogole了下,发现是javaee.jar包和mail.jar冲突了,解决办法是:删除javaee.jar中的mail和activation文件夹。重新测试又出现异常:
530 5.7.0 Must issue a STARTTLS command first
解决办法是加上:
props.put( "mail.smtp.starttls.enable" , "true" );
重新启动测试,打开126邮箱,成功收到邮件!