码迷,mamicode.com
首页 > 编程语言 > 详细

JavaMail发送简单邮件

时间:2015-06-04 18:50:12      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

非常简单的发送邮件实现,网上有很多啦,但还是自己写写记录下吧。

package cn.jmail.test;
 
import java.util.Properties;
 
import javax.mail.*;
import javax.mail.internet.*;
 
public class FirstMail {
    /**
     * 发送简单邮件方法
     * @param host    发送邮件服务器的IP
     * @param from    发送人地址
     * @param to    接收人地址
     * @param subject    邮件主题
     * @param text    内容
     * @param senderUsername    发送人的账户
     * @param senderPassword    发送人的密码
     * mail.smtp.auth 是否需要身份验证 一般都是需要的
     */
    public static void sendMail(String host, String from, String to, String subject, String text, 
            final String senderUsername, final String senderPassword){
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(senderUsername, senderPassword);
            }
        });
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setText(text);
            Transport.send(message);
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
     
    public static void main(String[] args) {
        String host = "smtp.163.com";
        String from = "xxxxxx@163.com";
        String to = "xxxxxxxx@qq.com";
        String subject = "Hello, this is a test email.";
        String text = "Hello,LiLei."; 
        String senderUsername = "xxxxxx@163.com";
        String senderPassword = "xxxxxx";
        FirstMail.sendMail(host, from, to, subject, text, senderUsername, senderPassword);
    }
}

嗯,当然不会少了 http://pan.baidu.com/s/1qW7LZvm

JavaMail发送简单邮件

标签:

原文地址:http://www.cnblogs.com/fu-yun/p/4552442.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!