惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
aimingoo的专栏
aimingoo的专栏
H
Help Net Security
腾讯CDC
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
酷 壳 – CoolShell
酷 壳 – CoolShell
MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
有赞技术团队
有赞技术团队
美团技术团队
雷峰网
雷峰网
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 司徒正美
博客园_首页
Recent Announcements
Recent Announcements
云风的 BLOG
云风的 BLOG
B
Blog RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
D
Docker
博客园 - Franky
Jina AI
Jina AI

博客园 - AlleNny

AFW短信防火墙 v1.0 beta 发布 [原创]从硬盘安装Fedora Core 6 Windows XP 使用技巧 中国教育十大谎言 Windows Vista演示“胡言乱语” 正则表达式--递归匹配与非贪婪匹配 正则表达式-分组构造 正则表达式-替换和分组 Tricks of command line commands IIS下配置Mantis+PHP+MYSQL环境[转] JAAS:灵活的Java安全机制[转] 中国十大害人的“俗话”[转]----好文章共同分享 Quake 4 最佳开源软件一览 那些温暖的碎肉沫——DOOM 3杂感 SQL注入不完全思路与防注入程序 Modify Eclipse parameter to support VSS plugin Oracle 的一些小技巧 俺的新电脑的配置,嘿嘿
如何用JavaMail发邮件
AlleNny · 2006-11-28 · via 博客园 - AlleNny


这篇文章是要介绍如何要用JavaMail通过需认证的SMTP服务器发HTML格式的邮件。
首先在sun网站上下载JavaMail的实现,和JAF的实现(不知道为啥不放在一起),加入你的classpath。

代码先从Authenticator继承一个class,比如叫SMTPAuthenticator,这个要用于和SMTP服务器连接时做认证的。

class SMTPAuthenticator extends Authenticator {
    
private String user;

    
private String password;

    
public SMTPAuthenticator(String s, String s1) {
        user 
= s;
        password 
= s1;
    }


    
public PasswordAuthentication getPasswordAuthentication() {
        
return new PasswordAuthentication(user, password);
    }


}

然后开始发邮件,

    Session sendMailSession = null;
    SMTPTransport transport 
= null;
    Properties props 
= new Properties();

    
// 与服务器建立Session的参数设置
    props.put("mail.smtp.host""smtp.163.com"); // 写上你的SMTP服务器。
    props.put("mail.smtp.auth""true"); // 将这个参数设为true,让服务器进行认证。
    SMTPAuthenticator auth = new SMTPAuthenticator("user""mypassword"); // 不用多说,用户名,密码。

    sendMailSession 
= Session.getInstance(props, auth); // 建立连接。
    
// SMTPTransport用来发送邮件。
    transport = (SMTPTransport) sendMailSession.getTransport("smtp");
    transport.connect();
    
// 创建邮件。
    Message newMessage = new MimeMessage(sendMailSession);
    newMessage.setFrom(
new InternetAddress("me@163.com"));
    newMessage.setRecipient(Message.RecipientType.TO, 
new InternetAddress("somebody@gmail.com"));
    newMessage.setSubject(
"This a test mail for Java Mail API);
    newMessage.setSentDate(new Date());
    
    
// 使用MimeMultipart和MimeBodyPart才能发HTML格式邮件。
    BodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(generateEmailBody(), 
"text/html;charset=gb2312"); // 发一个HTML格式的
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(bodyPart);
    newMessage.setContent(mp);

    Transport.send(newMessage);

OK,邮件发出去啦~~