Java使用qq邮箱发送email

前提:

qq邮箱要开通pop3服务协议,操作:qq邮箱-设置-账户-开启pop3,并记录生成的验证码。

执行代码:

public class MailUtil {

    private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static final String SMTP_HOST = "smtp.qq.com";
    private static final String SMTP_PORT = "465";
    private static final String SMTP_USER = "[email protected]";
    private static final String SMTP_SENDER = "[email protected]";
    private static final String SMTP_PASSWORD = "******"; //******

    public static boolean send(String toRecipient, String subject, String text) {
        List<String> toRecipients = new ArrayList<>();
        toRecipients.add(toRecipient);
        return send(toRecipients, subject, text, false, null);
    }

    /**
     * 邮件发送
     * @param toRecipient 接收人
     * @param subject 主题
     * @param html 内容
     * @return
     */
    public static boolean sendHtml(String toRecipient, String subject, String html) {
        List<String> toRecipients = new ArrayList<>();
        toRecipients.add(toRecipient);
        return send(toRecipients, subject, html, true, null);
    }

    public static boolean send(List<String> toRecipients, String subject, String content, boolean isHtml, List<String> attachmentNames) {
        //验证和处理邮箱地址
        if (SMTP_HOST == null || SMTP_PORT == null || SMTP_USER == null
                || SMTP_PASSWORD == null || SMTP_SENDER == null) {
            return false;
        }
        if (toRecipients == null) {
            return false;
        }
        Properties properties = new Properties();
		properties.put("mail.smtp.host", SMTP_HOST);
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.socketFactory.class", SSL_FACTORY);//使用JSSE的SSL socketfactory来取代默认的socketfactory
		properties.put("mail.smtp.socketFactory.fallback", "false");//只处理SSL的连接,对于非SSL的连接不做处理
		properties.put("mail.smtp.port", SMTP_PORT);
		properties.put("mail.smtp.socketFactory.port", SMTP_PORT);

        Session session = Session.getDefaultInstance(
                properties, new Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(SMTP_USER, SMTP_PASSWORD);
                    }
                });
		//session.setDebug(true); //debug信息
		MimeMessage message = new MimeMessage(session);

        try {
			// 发件人
			Address address = new InternetAddress(SMTP_SENDER);
			message.setFrom(address);
			// 收件人
			for (String recipient : toRecipients) {
				Address toAddress = new InternetAddress(recipient);
				message.addRecipient(MimeMessage.RecipientType.TO, toAddress);
			}
            toRecipients.clear();
			// 主题
			message.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
			// 时间
			message.setSentDate(new Date());
            // 主体
			Multipart multipart = new MimeMultipart();
			// 主体:正文
			BodyPart bodyPart = new MimeBodyPart();
            if (isHtml) {
                bodyPart.setContent(content, "text/html; charset=utf-8");
            } else {
                bodyPart.setText(content);
            }
			multipart.addBodyPart(bodyPart);
			// 主体:附件
            if (attachmentNames != null && attachmentNames.size() > 0) {
                for (String fileName : attachmentNames) {
                    BodyPart adjunct = new MimeBodyPart();
                    FileDataSource fileDataSource = new FileDataSource(fileName);
                    adjunct.setDataHandler(new DataHandler(fileDataSource));
                    adjunct.setFileName(MimeUtility.encodeText(fileDataSource.getName(), "UTF-8", "B"));
                    multipart.addBodyPart(adjunct);
                }
                attachmentNames.clear();
            }
			message.setContent(multipart);
			message.saveChanges();
            Transport.send(message);
            return true;
		} catch (Exception e) {
            e.printStackTrace();
            return false;
		}
    }

    public static void main(String[] args) {
        boolean result = sendHtml("[email protected]", "测试邮件", "<html><head></head><body><h1>你好</h1><p>这是正文, 这是<i>正文</i>.</p></body></html>");
        System.out.println(result);
    }
}


猜你喜欢

转载自blog.csdn.net/guandongsheng110/article/details/76984941