Java 实现邮件的自动发送

来源:互联网 发布:sql declare 用法 编辑:程序博客网 时间:2024/06/05 20:53

网上已经有很多实现的例子了,此处只是总结记录以便日后查看
发送邮件需要两个jar包:mail.jar和activation.jar

  1. 构建一个身份验证类
package com.shusheng007.sstx.email;import javax.mail.Authenticator;import javax.mail.PasswordAuthentication;public class SMTPAuthenticator extends Authenticator {    private String user;    private String password;    public SMTPAuthenticator(String user, String password) {        this.user = user;        this.password = password;    }    public PasswordAuthentication getPasswordAuthentication(){        return new PasswordAuthentication(user, password);    }}  
  1. 构建并发送邮件
package com.shusheng007.sstx.email;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Properties;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeMessage;import com.sun.mail.smtp.SMTPTransport;public boolean sendEmail(String sendUser,String sendPassWord,                    String sendAddress, String toAddress,String content)     {        boolean flag=false;        try        {            Session sendMailSession = null;            SMTPTransport transport = null;            Properties props = new Properties();            // 与服务器建立Session的参数设置            props.put("mail.smtp.host", "smtp.163.com"); // 写上你的SMTP服务器。            props.put("mail.smtp.auth", "true"); // 将这个参数设为true,让服务器进行认证。            //用户名,密码。            SMTPAuthenticator auth = new SMTPAuthenticator(sendUser,                                                              sendPassWord);                 sendMailSession = Session.getInstance(props, auth); // 建立连接。            // SMTPTransport用来发送邮件。            transport =         (SMTPTransport)sendMailSession.getTransport("smtp");            transport.connect();            // 创建邮件。            Message newMessage = new MimeMessage(sendMailSession);            newMessage.setFrom(new InternetAddress(sendAddress));            newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));            newMessage.setSubject("神算天下用户密码重置");            newMessage.setSentDate(new Date());            newMessage.setText("密码已经重置为:"+content+" 请尽快登录修改密码");            // 使用MimeMultipart和MimeBodyPart才能发HTML格式邮件。            //BodyPart bodyPart = new MimeBodyPart();            //bodyPart.setContent(generateEmailBody(), "text/html;charset=gb2312"); // 发一个HTML格式的            //Multipart mp = new MimeMultipart();            //mp.addBodyPart(bodyPart);            //newMessage.setContent(mp);                Transport.send(newMessage);                     flag=true;        }         catch (MessagingException e) {            flag=false;            e.printStackTrace();        }               return flag;    }
0 0
原创粉丝点击