首先導入mail的jar包
然後代碼如下
package aaa;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailClient {
// 用戶名
protected static String username = "[email protected]";
// 密碼
protected static String passwrod = "axdjxsinansijhbh";
// 服務器地址
protected static String hostIp = "smtp.qq.com";
// 需要驗證
protected static String auth = "true";
// 端口號 主
// ssl 端口號
protected String sslport = "465";
public static void sendEmail1() {
/**
* 1連接郵件服務器 2創建郵件對象 3郵件發送
*/
Properties pros = System.getProperties();
// 你要鏈接那個郵箱服務器
pros.put("mail.smtp.host", hostIp);
// 你要鏈接發送的的端口號
pros.put("mail.smtp.port", "25");
// 是否啓用驗證
pros.put("mail.smtp.auth", auth);
// ssl驗證
pros.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
// ssl端口號
pros.put("mail.smtp.socketFactory.port", "465");
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(username, passwrod);
}
};
Session session = Session.getInstance(pros, auth);
session.setDebug(true);
// 2創建郵件對象
try {
Message message = new MimeMessage(session);
// 發件人
message.setFrom(new InternetAddress("[email protected]"));
message.setContent("早飯早飯早飯早飯早飯早飯<a href='www.wulilang.cn'>點擊我</a>",
"text/html;charset=utf-8");
message.addRecipient(RecipientType.TO, new InternetAddress(
"[email protected]"));
message.setSentDate(new Date());
message.setSubject("主題");
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
sendEmail1();
}
}