java发送邮件

maven

<dependency>
	<groupId>javax.mail</groupId>
	<artifactId>mail</artifactId>
	<version>1.4.1</version>
</dependency>

mail.properties

#----------------这两个是构建session必须的字段----------
#smtp服务器
mail.smtp.host=*****
#身份验证
mail.smtp.auth=true
#--------------------------------------------------------------

#发送者的邮箱用户名
mail.sender.username=****
#发送者的邮箱密码
mail.sender.password=***
#邮件发送人  
mail.show.name=***

PropertiesFileUtil

public class PropertiesFileUtil {
    private static Log log = LogFactory.getLog(new PropertiesFileUtil().getClass());

    /**
     * 根据键获得相应的值
     * @param path 路径
     * @param key 键
     * @return
     */
    public static String getValueByKey(String path, String key) {
      
        Properties properties = getProperties(path);
        return  properties.getProperty(key);
    }

    /**
     * 获取配置文件
     * @param path
     * @return
     */
    public static Properties getProperties(String path){
        try {
            //获取绝对路径
            String filePath = PropertiesFileUtil.class.getResource("/" + path).toString();
            //截掉路径的”file:“前缀
            filePath = filePath.substring(5);
            filePath = filePath.replace("%20", " ") ;
            Properties props = new Properties();
            InputStream in = new BufferedInputStream(new FileInputStream(filePath));
            props.load(in);
            in.close();
            return props ;
        } catch (IOException e) {
            log.error(e.toString());
            return null;
        }
    }
    public static void main(String[] args) {
        System.out.println(getValueByKey("url.properties", "url"));
    }
}


javaMailUtil

public class JavaMailUtil {
    /**
     * Message对象将存储我们实际发送的电子邮件信息,
     * Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail session。
     */
    private MimeMessage message;

    /**
     * Session类代表JavaMail中的一个邮件会话。
     * 每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。
     *
     * JavaMail需要Properties来创建一个session对象。
     * 寻找"mail.smtp.host"    属性值就是发送邮件的主机
     * 寻找"mail.smtp.auth"    身份验证,目前免费邮件服务器都需要这一项
     */
    private Session session;

    /***
     * 邮件是既可以被发送也可以被受到。JavaMail使用了两个不同的类来完成这两个功能:Transport 和 Store。
     * Transport 是用来发送信息的,而Store用来收信。对于这的教程我们只需要用到Transport对象。
     */
    private Transport transport;

    private String mailHost="";
    private String sender_username="";
    private String sender_password="";
    private String showName="";


    private Properties properties;

    private static class JavaMailUtilInstance {
        private static JavaMailUtil javaMailUtil = new JavaMailUtil();
    }

    public static JavaMailUtil getInstance() {
        return JavaMailUtilInstance.javaMailUtil;
    }

    /*
     * 初始化方法
     */
    public JavaMailUtil() {
        try {
            properties = PropertiesFileUtil.getProperties("mail.properties");
            this.mailHost = properties.getProperty("mail.smtp.host");
            this.sender_username = properties.getProperty("mail.sender.username");
            this.sender_password = properties.getProperty("mail.sender.password");
            this.showName = properties.getProperty("mail.show.name");
        } catch (Exception e) {
            e.printStackTrace();
        }

        session = Session.getInstance(properties);
//        session.setDebug(false);//开启后有调试信息
        message = new MimeMessage(session);
    }

    /**
     * 发送邮件
     *
     * @param subject
     *            邮件主题
     * @param sendHtml
     *            邮件内容
     * @param receiveUser
     *            收件人地址
     */
    public void doSendHtmlEmail(String subject, String sendHtml,
                                String receiveUser) {
        try {
            // 发件人
            //InternetAddress from = new InternetAddress(sender_username);
            // 下面这个是设置发送人的Nick name
            InternetAddress from = new InternetAddress(MimeUtility.encodeWord(showName)+" <"+sender_username+">");
            message.setFrom(from);

            // 收件人
            InternetAddress to = new InternetAddress(receiveUser);
            message.setRecipient(Message.RecipientType.TO, to);//还可以有CC、BCC

            // 邮件主题
            message.setSubject(subject);

            String content = sendHtml.toString();
            // 邮件内容,也可以使纯文本"text/plain"
            message.setContent(content, "text/html;charset=UTF-8");

            // 保存邮件
            message.saveChanges();

            transport = session.getTransport("smtp");
            // smtp验证,就是你用来发邮件的邮箱用户名密码
            transport.connect(mailHost, sender_username, sender_password);
            // 发送
            transport.sendMessage(message, message.getAllRecipients());
            //System.out.println("send success!");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(transport!=null){
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        JavaMailUtil se = new JavaMailUtil();
        se.doSendHtmlEmail("邮件主题", "邮件内容html", "接收人邮箱");
    }
}


 


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值