java代码简单实现发送邮件
1.首先需要下载 email相关jar包(activation.jar,mail.jar)。
2.由于公司不能上外网,我配置的为本地的邮箱服务器(易邮邮件服务器)。如果是互联网邮箱服务器
pro.put("mail.smtp.host", "localhost"); localhost改为互联网服务器地址,如163邮箱就是smtp.163.com。
3.实现代码如下:(smtp是邮件发送的协议,pop3为邮箱的客户端获取邮件的协议,想了解可以百度下)
package sendemail; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; 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 test { public void sendemail(String to,String content,String title) throws AddressException, MessagingException{ String user ="bbb"; //邮箱账户 String pwd="123"; //邮箱登陆密码 Properties pro=new Properties(); pro.put("mail.smtp.host", "localhost"); //设置主机地址,此处为本机地址。如果使用163邮箱。该出应配置smtp.163.com pro.put("mail.smtp.auth", true); //是否开启验证 Session instance = Session.getInstance(pro, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // TODO Auto-generated method stub return new PasswordAuthentication(user, pwd); } }); instance.setDebug(true); Message m=new MimeMessage(instance); m.setFrom(new InternetAddress("bbb@sl.com")); //发件人 m.addRecipient(RecipientType.TO, new InternetAddress(to)); //收件人 m.setSubject(title);//设置标题 m.setContent(content,"text/html;charset=UTF-8"); //设置文本内容,和发送文本的格式 Transport.send(m);//调用该方法进行发送 } public static void main(String[] args) { test t=new test(); try { t.sendemail("aaa@sl.com", "内容", "标题"); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
运行之后,出现结果,如图: