java 发送邮件简单实例
项目结构:
全部代码:
EmailAuthenticator.java
package com.gjw.test;import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;public class EmailAuthenticator extends Authenticator{ private String username; private String userpsd; public EmailAuthenticator(String username, String userpsd) { this.username = username; this.userpsd = userpsd; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpsd() { return userpsd; } public void setUserpsd(String userpsd) { this.userpsd = userpsd; } @Override protected PasswordAuthentication getPasswordAuthentication() { // TODO Auto-generated method stub return super.getPasswordAuthentication(); } }
package com.gjw.test;import java.util.Properties;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;public class MailSender{ public static void main(String[] args) throws Exception { //这是邮件服务器地址 String smtp = "smtp.163.com"; //用户邮箱地址 //用自己的邮箱啊 String from = "gaojunwei@163.com"; //要发送的邮箱 String to = "gaojunwei@qq.com"; //构造用户身份验证验证对象,参数为用户名和口令 EmailAuthenticator auth = new EmailAuthenticator("gaojunwei","123456"); //获取系统属性对象 Properties props = System.getProperties(); //设置邮件服务器和是否身份验证 props.put("mail.smtp.host", smtp); /* 如果写成这样 props.put("mail.smtp.auth", true); * 会爆 com.sun.mail.smtp.SMTPSendFailedException:异常 * 应该写成 props.put("mail.smtp.auth", "true"); * */ props.put("mail.smtp.auth", "true"); //获得Session对象 Session session = Session.getInstance(props,(Authenticator)auth); //以session作为参数建立MimeMessage对象 //这里Mime是支持该协议的类,用来描述邮件的内容 MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to)); msg.setSubject("只是测试"); String s = "测试内容"; msg.setText(s); //设置好MimeMessage后,从Session中建立Transport对象 //Transport对象用于发送邮件信息,getTransport的参数 //表明发送邮件使用的协议。 Transport transport = session.getTransport("smtp"); transport.connect(smtp,"gaojunwei@163.com","123456"); transport.sendMessage(msg,msg.getAllRecipients()); transport.close(); System.out.println("邮件发送成功"); }}