使用Java发送邮件

来源:互联网 发布:特别好的句子 知乎 编辑:程序博客网 时间:2024/06/07 22:12
//Java Web发送邮件


try {
Properties prop = new Properties();

//在属性中设置发送邮件服务器地址与协议
prop.setProperty("mail.host", "smtp.126.com"); //邮件服务器地址
prop.setProperty("mail.transport.protocol", "smtp"); //使用的协议
prop.setProperty("mail.stmp.auth", "true"); //是否需要身份验证

//使用JavaMail发送邮件的5个步骤
//1. 创建session
javax.mail.Session session = javax.mail.Session.getInstance(prop);
//开启session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2. 通过session得到Transport对象
Transport ts = session.getTransport();
/*3. 使用邮箱的用户名和密码链接邮件服务器时,发件人需要提交邮箱的用户名
和密码给SMTP服务器
*/
ts.connect("smtp.126.com", 发件人邮箱, 发件人邮箱密码);
//4. 创建邮件
//① 创建邮件对象
Message msg = new MimeMessage(session);
//② 指明邮件发件人
msg.setFrom(new InternetAddress(发件人邮箱));
//③ 指明收件人邮箱
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(收件人邮箱));
//④ 邮件主题
msg.setSubject(邮件主题);
//⑤ 邮件内容
mes.setContent(邮件内容, "text/html;charset=UTF-8");

//5. 发送邮件
ts.sendMessage(msg, msg.getAllRecipients());
ts.close();
} catch (Exception ex) {

}


package com.hcw.javamail;


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 JavaMailDemo1 {
public static void main(String[] args) throws MessagingException {
//创建session对象
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");//没写的时候  javax.mail.NoSuchProviderException: Invalid protocol: null
Session session = Session.getInstance(props);
session.setDebug(true);

//创建message对象
Message msg = new MimeMessage(session);
msg.setText("你好吗?");
msg.setFrom(new InternetAddress("zhangsan@163.com"));
Transport transport = session.getTransport();
transport.connect("smtp.163.com",25, "zhangsan", "123456");
transport.sendMessage(msg,new Address[]{new InternetAddress("lisi@sina.com")});
//transport.send(msg,new Address[]{new InternetAddress("lisi@sina.com")});
transport.close();
}
}

原创粉丝点击