Java 邮件(JavaMail)

来源:互联网 发布:python基础环境搭建 编辑:程序博客网 时间:2024/06/11 00:37

Java 邮件(JavaMail)

  1. 创建MailSenderInfo Bean,用来存储邮件使用的基本信息。
/** * 1. 发送邮件需要使用的基本信息 * @author mazaiting */public class MailSenderInfo {    /** 发送邮件的服务器ip */    private String mailServerHost;    /** 发送邮件的服务器端口 */    private String mailServerPort = "25";    /** 邮件发送者的地址 */    private String fromAddress;    /** 邮件接收者的地址 */    private String toAddress;    /** 登录邮件发送服务器的用户名 */    private String username;    /** 登录邮件发送服务器的密码 --授权密码*/    private String password;    /** 是否需要身份验证 */    private boolean isValidate = false;    /** 邮件主题 */    private String subject;    /** 邮件文本内容 */    private String content;    /** 邮件附件的文件 */    private List<File> fileList;    /**     * 获得邮件会话属性     * @throws GeneralSecurityException  证书安全异常     */    public Properties getProperties() throws GeneralSecurityException {        Properties p = new Properties();        p.put("mail.smtp.host", this.mailServerHost);        p.put("mail.smtp.port", this.mailServerPort);        p.put("mail.smtp.auth", isValidate ? "true" : "false");        // 进行证书验证        MailSSLSocketFactory mssf = new MailSSLSocketFactory();        mssf.setTrustAllHosts(true);        p.put("mail.smtp.ssl.enable", true);        p.put("mail.smtp.ssl.socketFactory", mssf);        return p;    }    public String getMailServerHost() {        return mailServerHost;    }    public void setMailServerHost(String mailServerHost) {        this.mailServerHost = mailServerHost;    }    public String getMailServerPort() {        return mailServerPort;    }    public void setMailServerPort(String mailServerPort) {        this.mailServerPort = mailServerPort;    }    public String getFromAddress() {        return fromAddress;    }    public void setFromAddress(String fromAddress) {        this.fromAddress = fromAddress;    }    public String getToAddress() {        return toAddress;    }    public void setToAddress(String toAddress) {        this.toAddress = toAddress;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    public boolean isValidate() {        return isValidate;    }    public void setValidate(boolean isValidate) {        this.isValidate = isValidate;    }    public String getSubject() {        return subject;    }    public void setSubject(String subject) {        this.subject = subject;    }    public String getContent() {        return content;    }    public void setContent(String content) {        this.content = content;    }    public List<File> getFileList() {        return fileList;    }    public void setFileList(List<File> fileList) {        this.fileList = fileList;    }}
  1. 密码验证管理
/** * 2. 简单的验证管理 * @author mazaiting */public class SimpleAuthenticator extends Authenticator{    /**用户名*/    private String username = null;    /**密码*/    private String password = null;    public SimpleAuthenticator(String username, String password) {        this.username = username;        this.password = password;    }        protected PasswordAuthentication getPasswordAuthentication() {        return new PasswordAuthentication(username, password);    }}
  1. 实现简单邮件服务器
/** * 3. 简单邮件 * @author mazaiting */public class SimpleMailServer {    /**     * 以文本格式发送邮件     * @param mailInfo 待发送的邮件信息     * @return true 发送成功; false 发送不成功     */    public boolean sendTextMail(MailSenderInfo mailInfo) {        try {            // 判断是否需要身份验证            SimpleAuthenticator authenticator = null;            Properties properties = mailInfo.getProperties();            if (mailInfo.isValidate()) {                // 如果需要身份验证, 则创建一个密码验证器                authenticator = new SimpleAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());            }            // 根据邮件会话属性和密码验证器构造一个发送邮件的Session            Session sendMailSession = Session.getDefaultInstance(properties, authenticator);            // 根据Session创建一个邮件信息            Message mailMessage = new MimeMessage(sendMailSession);            // 创建邮件发送者地址            Address from = new InternetAddress(mailInfo.getFromAddress());            // 设置邮件消息的发送者            mailMessage.setFrom(from);            // 创建邮件的接收者地址,并设置到邮件消息中            Address to = new InternetAddress(mailInfo.getToAddress());            mailMessage.setRecipient(Message.RecipientType.TO, to);            // 设置邮件消息的主题            mailMessage.setSubject(mailInfo.getSubject());            // 设置邮件消息发送时间            mailMessage.setSentDate(new Date());            // 设置邮件消息的主要内容            String mailContent = mailInfo.getContent();            mailMessage.setText(mailContent);            // 发送邮件            Transport.send(mailMessage);            return true;        } catch (Exception e) {            e.printStackTrace();        }        return false;    }    /**     * 以HTML格式发送邮件     *      * @param mailInfo     *            待发送的邮件     * @return true 发送成功; false 发送失败。     */    public boolean sendHtmlMail(MailSenderInfo mailInfo) {        try {            // 判断是否需要身份认证            SimpleAuthenticator authenticator = null;            Properties properties = mailInfo.getProperties();            // 如果需要身份认证, 则创建一个密码验证器            if (mailInfo.isValidate()) {                authenticator = new SimpleAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());            }            // 根据邮件会话属性和密码验证器构造一个发送邮件的Session            Session sendMailSession = Session.getDefaultInstance(properties, authenticator);            // 根据Session创建一个邮件消息            Message mailMessage = new MimeMessage(sendMailSession);            // 创建邮件发送者地址            Address from = new InternetAddress(mailInfo.getFromAddress());            // 设置邮件消息的发送者            mailMessage.setFrom(from);            // 创建邮件的接收者地址, 并设置到邮件消息中            Address to = new InternetAddress(mailInfo.getToAddress());            // Message.RecipientType.TO属性表示接收者的类型为TO            mailMessage.setRecipient(Message.RecipientType.TO, to);            // 设置邮件消息的主题            mailMessage.setSubject(mailInfo.getSubject());            // 设置邮件消息发送的时间            mailMessage.setSentDate(new Date());            // MiniMultipart类是一个容器,包含MimeBodyPart类型的对象            Multipart mainPart = new MimeMultipart();                        if (null != mailInfo.getContent()) {                setContent(mailInfo, mainPart);            }            if (null != mailInfo.getFileList() && mailInfo.getFileList().size() > 0) {                addAttachment(mailInfo.getFileList(), mainPart);            }                                    // 将MiniMultipart对象设置为邮件内容            mailMessage.setContent(mainPart);            // 发送邮件            Transport.send(mailMessage);            return true;        } catch (Exception e) {            e.printStackTrace();        }        return false;    }    /**     * 设置内容     * @param mailInfo 邮件信息     * @param mainPart 容器     * @throws MessagingException 消息异常     */    public void setContent(MailSenderInfo mailInfo, Multipart mainPart) throws MessagingException {        // 创建一个包含HTML内容的MimeBodyPart        BodyPart textContent = new MimeBodyPart();        // 设置HTML内容        textContent.setContent(mailInfo.getContent(), "text/html; charset=utf-8");        mainPart.addBodyPart(textContent);    }        /**     * 添加附件     * @param filePath 文件路径     * @param fileName 文件名     * @param mainPart 容器     * @throws MessagingException 消息异常     */    public void addAttachment(List<File> fileList, Multipart mainPart) throws MessagingException{        for (int i = 0; i < fileList.size(); i++){            File file = fileList.get(i);            BodyPart fileContent = new MimeBodyPart();            DataSource source = new FileDataSource(file.getAbsolutePath());            fileContent.setDataHandler(new DataHandler(source));            fileContent.setFileName(file.getName());            mainPart.addBodyPart(fileContent);        }    }}
  1. 主函数使用
public class Client {    public static void main(String[] args) {                // 设置邮件        MailSenderInfo mailInfo = new MailSenderInfo();        // 设置服务器主机名        mailInfo.setMailServerHost("smtp.qq.com");        // 设置服务器端口        mailInfo.setMailServerPort("465");        // 设置密码验证        mailInfo.setValidate(true);        // 设置用户名        mailInfo.setUsername("1449689807@qq.com");        // 设置登录验证需要的密码        mailInfo.setPassword("****************");// 设置为自己的验证密码        // 设置发送者地址        mailInfo.setFromAddress("1449689807@qq.com");        // 设置接收者地址        mailInfo.setToAddress("1425941077@qq.com");        // 设置邮件标题        mailInfo.setSubject("邮件标题");        // 设置邮件内容        mailInfo.setContent("邮件内容");        // 设置邮件携带的附件//      List<File> fileList = new ArrayList<>();//      fileList.add(new File("C:\\Users\\Administrator\\Desktop\\password.png"));//      mailInfo.setFileList(fileList);                // 发送邮件        SimpleMailServer sms = new SimpleMailServer();//      sms.sendTextMail(mailInfo);// 发送文本格式        sms.sendHtmlMail(mailInfo);// 发送html格式          }}
  1. 遇到的问题
    查看详情

  2. Android 使用Javamail发送邮件时,要将第一步中的getProperties()函数更改为如下内容:

    /**     * 获得邮件会话属性     * @throws GeneralSecurityException  证书安全异常     */    Properties getProperties() throws GeneralSecurityException {        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");        CommandMap.setDefaultCommandMap(mc);        Properties p = new Properties();        p.put("mail.smtp.host", this.mailServerHost);        p.put("mail.smtp.port", this.mailServerPort);        p.put("mail.smtp.auth", isValidate ? "true" : "false");        // 进行证书验证        MailSSLSocketFactory mssf = new MailSSLSocketFactory();        mssf.setTrustAllHosts(true);        p.put("mail.smtp.ssl.enable", true);        p.put("mail.smtp.ssl.socketFactory", mssf);        return p;    }

其中需要activation.jar,点击下载。或者Gradle直接依赖compile 'com.sun.mail:android-mail:1.6.0',使用Gradle依赖之后,之前用到的mail.jar与此处用到的activation.jar都必须要删除,否则会重复编译jar。

示例代码下载

原创粉丝点击