java邮箱入门

  • 来源:csdn
  • 更新日期:2018-03-13

摘要:首先,下载所需要的包,maven中下载地址:http://mvnrepository.com/artifact/com.sun.mail/javax.mail 直接下载地址:https://javaee.github.io/javamail/ import java.util.Date; import java.util.Properties; import javax.m

首先,下载所需要的包,maven中下载地址:http://mvnrepository.com/artifact/com.sun.mail/javax.mail

直接下载地址:https://javaee.github.io/javamail/

t012845f48ece5bb815.jpg

 

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

public class EmailUtil {
/**
* host 邮箱服务器,例如smtp.163.com
* port 端口号
* username 邮箱用户名
* password 并非邮箱的登录密码,而是邮箱的授权密码(需要申请)
*/
private static String host="smtp.163.com";
private static int port=25;
private static String username="157xxxxx@163.com";
private static String password="yoonbxxxx";

/**
*
* @param sendTo 选择要发送对象的邮箱地址
* @param subject 邮件的主题
* @param text 邮件的内容
*/
public static void sendEmail(String sendTo,String subject,String text) {
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
Session session = Session.getInstance(props, null);


try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom("15705695230@163.com");
msg.setRecipients(Message.RecipientType.TO,
sendTo);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(text);
Transport.send(msg, username, password);
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}

 

 

在另一个类中直接导入包,使用即可

EmailUtil.sendEmail("12345@qq.com", "邮件主题", "邮件内容");