java 发送邮件

来源:互联网 发布:php 字母a加1 编辑:程序博客网 时间:2024/06/06 16:31

导入jar包

<!-- 发送邮件--> <dependency>     <groupId>javax.mail</groupId>     <artifactId>mail</artifactId>     <version>1.4.7</version> </dependency>


package com.utils;import javax.activation.DataHandler;import javax.activation.DataSource;import javax.activation.FileDataSource;import javax.mail.*;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.MimeMultipart;import javax.xml.transform.Result;import java.util.Properties;/** * Author:   linjunit * Version: * Date:     2017/11/10 0010 * Description: * Modification  History: * Date            Author            Version            Description * -------------------------------------------------------------- * Why & What is modified: */public class SendEmail {    /**     * 发送邮件     * @param to 发件人     * @param from 收件人     * @param host host地址 可选参数     * @return     */    public  static boolean  SendEmail(String to,String from,String host){        boolean flag=false;        // 获取系统属性对象        Properties properties = System.getProperties();        // 设置邮件服务器        properties.setProperty("mail.smtp.host", host);        // 获取默认的Session对象。        Session mailSession = Session.getDefaultInstance(properties);        try{            // 创建一个默认的MimeMessage对象。            MimeMessage message = new MimeMessage(mailSession);            // 设置 From: 头部的header字段            message.setFrom(new InternetAddress(from));            // 设置 To: 头部的header字段            message.addRecipient(Message.RecipientType.TO,                    new InternetAddress(to));            // 设置 Subject: header字段            message.setSubject("This is the Subject Line!");            // 创建消息部分            BodyPart messageBodyPart = new MimeBodyPart();            // 填充消息            messageBodyPart.setText("This is message body");            // 创建多媒体消息            Multipart multipart = new MimeMultipart();            // 设置文本消息部分            multipart.addBodyPart(messageBodyPart);            // 附件部分            messageBodyPart = new MimeBodyPart();            String filename = "file.txt";            DataSource source = new FileDataSource(filename);            messageBodyPart.setDataHandler(new DataHandler(source));            messageBodyPart.setFileName(filename);            multipart.addBodyPart(messageBodyPart);            // 发送完整消息            message.setContent(multipart );            // 发送消息            Transport.send(message);            String title = "Send Email";        flag=true;        }catch (MessagingException mex) {            mex.printStackTrace();           flag=false;        }        return flag;    }}

原创粉丝点击