---
title: "java 发邮件"
author: "LHacker"
date: "2012-08-01T14:03:42Z"
tags: []
categories: ["行业应用"]
slug: "java"
draft: false
lastmod: "2012-08-01T14:06:44Z"
id: 1615592
url: "https://lhacker.iteye.com/blog/1615592"
---

介绍两种发邮件的方式，也是从网上得来的资料，收藏。

 

一，commons-email方式

     导入commons-email-1.1.jar包，代码如下：

 

 

public void sendMail() {   

        SimpleEmail email = new SimpleEmail();   

        email.setTLS(true);       

        email.setHostName("smtp.163.com");   

        email.setAuthentication("\*\*@163.com", "密码\*\*\*\*"); // 用户名和密码   

 

        try {   

            email.addTo("\*\*@qq.com"); // 接收方   

            email.setFrom("\*\*@163.com"); // 发送方   

            email.setSubject("Dylan's email"); // 标题   

            email.setCharset("GBK");   

            email.setMsg("hello,i am Dylan"); // 内容   

            email.send();   

 

        } catch (EmailException e) {   

            e.printStackTrace();   

        }   

    } 

 

 

二 spring方式

 

导入spring所需jar包，代码如下：

 

（1）配置emailsender

 

                &lt;bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt;

&lt;property name="host" value="smtp.qq.com" /&gt;

&lt;property name="port" value="25" /&gt;

&lt;property name="username" value="\*\*@qq.com" /&gt;

&lt;property name="password" value="密码\*\*" /&gt;

&lt;property name="javaMailProperties"&gt;

&lt;props&gt;

&lt;prop key="mail.smtp.auth"&gt;true&lt;/prop&gt;

&lt;/props&gt;

&lt;/property&gt;

&lt;/bean&gt;

 

（2）代码

public void sendMail() {   

 

               ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/application-root.xml");  

       JavaMailSender mailSender= (JavaMailSender) context.getBean("mailSender");  

       SimpleMailMessage mail = new SimpleMailMessage();  

       mail.setFrom("\*\*@qq.com");  

       mail.setTo("\*\*@163.com");  

       mail.setSubject(" 测试spring Mail");  

       mail.setText("hello,java");  

       mailSender.send(mail);  

}

 

方法都很简单。主要确保邮箱开启了SMTP服务