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

JAVA用email.jar发送邮件

时间:2014-11-06 19:22:59      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   java   sp   

1 jar包

 email.jar包,网上下载

2 源代码

package zjr.amy.emil.test;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

/**
 * 发邮件测试
 * @author zhujinrong
 *
 */
public class MailTest {
    
    static Authenticator auth = new Authenticator(){
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            // TODO Auto-generated method stub
            return new PasswordAuthentication("1251759009@qq.com", "密码");
        }
    };

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) throws MessagingException {
        // TODO Auto-generated method stub
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.from", "1251759009@qq.com");
        Session session = Session.getInstance(props, auth);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO, "2804163771@qq.com");
        msg.setSubject("JavaMail hello world example");
        msg.setSentDate(new Date());
        msg.setText("<html><body><span style=‘color:red;‘>Hello world!</span></body></html>", "utf-8", "html");
        Transport.send(msg);
    }
}

3 运行结果

bubuko.com,布布扣

4 遇到的错误

Exception in thread "main" javax.mail.AuthenticationFailedException: 454 Authentication failed, please open smtp flag first!

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at zjr.amy.emil.test.MailTest.main(MailTest.java:46)

原因:没有qq邮箱没有开启smtp服务

解决方法:在QQ邮箱的设置里面,找到账户-》POP3/IMAP/SMTP选择开启POP3/SMTP服务

5 git地址

 git地址:https://github.com/HelloAmy/JavaStudy.git

JAVA用email.jar发送邮件

标签:style   blog   http   io   color   ar   os   java   sp   

原文地址:http://www.cnblogs.com/tianxue/p/4079543.html

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