java简单发送邮件

需要的jar 据说是: 

<dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.1</version>
        </dependency>

引入的jar:

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

发送的代码:

public static void sendMail() throws Exception{ 
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                PasswordAuthentication pa = new PasswordAuthentication("username", "password"); 
                return pa;
            }
        };
        Properties prop = new Properties(); 
        prop.setProperty("mail.host","smtp.126.com"); 
        prop.setProperty("mail.smtp.auth", "true"); 
        Session session =  Session.getDefaultInstance(prop,auth); 
        session.setDebug(true); 
        MimeMessage mm1 = new MimeMessage(session); 
        Address from = new InternetAddress("fromaddress");  //发件人
        mm1.setFrom(from); 
        mm1.setRecipient(RecipientType.TO,new InternetAddress("toaddress"));  //收件人
        mm1.setSubject("这是用Java发的邮件3"); 
        mm1.setContent("你好,这是用java发的邮件,3333再试一下", "text/plain;charset=UTF-8"); 
        mm1.setContent("你好,这是用java发的邮件,<a href='http://www.baidu.com'>百度</a>", "text/html;charset=UTF-8" );     
        Transport.send(mm1); 
    }

参考文章:http://www.jb51.net/article/80958.htm

原文地址:https://www.cnblogs.com/lishupeng/p/5619014.html