发送QQ邮件

摘要

java写的发送邮件功能,以qq邮箱作为发件人,收件邮件没有特殊要求。
需要注意的是发件qq邮箱需要开启POP3/STMP服务并生成授权码,发送邮件时把授权码当成密码使用。

 maven pom

    
        javax.mail
	mail
	1.4.7
    

发送邮件的方法

         /**
	 * 发送QQ邮件
	 * @param from 发件人
	 * @param to 收件人
	 * @param password 密码/授权码
	 * @param subject 主题
	 * @param content 内容
	 * @param debug 是否打印调试信息
	 * @throws Exception
	 */
	public void send(String from, String to, String password, String subject, String content, boolean debug) throws Exception{
		Properties properties = new Properties();
		if(debug){
			properties.setProperty("mail.debug", "true");
		}
		
		properties.setProperty("mail.smtp.auth", "true");
		properties.setProperty("mail.transport.protocol", "smtp");
		properties.setProperty("mail.smtp.host", "smtp.qq.com");
		properties.put("mail.smtp.ssl.enable", true);
		
		MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
		mailSSLSocketFactory.setTrustAllHosts(true);
		properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
		
		Session session = Session.getInstance(properties);
		
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(from));
		message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
		message.setSubject(subject);
		message.setText(content);
		
		Transport transport = session.getTransport();
		transport.connect(from, password);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	}

运行结果

        /**
	 * from
	 */
	public static final String SENDER_ADDRESS = "[email protected]";
	
	/**
	 * to
	 */
	public static final String RECIEVE_ADDRESS = "[email protected]";
	
	/**
	 * auth code
	 */
	public static final String AUTH_CODE = "aguwwkbojsct****";
	
	@Test
	public void test() throws Exception{
		send(SENDER_ADDRESS, RECIEVE_ADDRESS, AUTH_CODE, "test", "测试", true);
	}

发送QQ邮件_第1张图片

你可能感兴趣的:(JAVA,邮件,java,qq,邮件)