JMail是进行邮件开发的组件。由于所需要的jar非官方开发,需要自行下载所需jar包,我使用的是javamail-1.4.7。
不了解收发邮件过程的请先浏览我的另一片博客:电子邮件工作原理
大致步骤:
1. 创建Properties对象,并为该对象设置相应内容
2. 创建Session对象
3. 创建Message对象,这个对象封装邮件的信息,如发件人、收件人、主题等等
4. 创建Transport对象,利用这个对象发送邮件
总的来说就两个步骤:构造邮件对象(第3步,只不过在构建邮件时需要其它对象),发送邮件(第4步)
代码:
package com.zyh.demo;
import java.util.Properties;
import javax.mail.Address;
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;
public class Demo1 {
public static void main(String[] args) throws MessagingException {
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");//设置访问smtp服务器需要认证
props.setProperty("mail.transport.protocol", "smtp"); //设置访问服务器的协议
Session session = Session.getDefaultInstance(props);
session.setDebug(true); //打开debug功能
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]")); //设置发件人,163邮箱要求发件人与登录用户必须一致(必填),其它邮箱不了解
msg.setText("Hello world!"); //设置邮件内容
msg.setSubject("test"); //设置邮件主题
Transport trans = session.getTransport();
trans.connect("smtp.163.com", 25, "你的邮箱地址(@之前)", "邮箱密码"); //连接邮箱smtp服务器,25为默认端口
trans.sendMessage(msg, new Address[]{new InternetAddress("[email protected]")}); //发送邮件
trans.close(); //关闭连接
}
}
原文:http://blog.csdn.net/zyh5540/article/details/18953985