如何使用java發送郵件


  今天給你們帶來的是用java發送郵件,若有不足之處,敬請指教。html

  本次咱們利用QQ來發送郵件。java

1、配置步驟

  1. 打開郵箱的POP三、SMTP
  2. 導入包
  3. 配置郵件發送類
  4. 編寫郵件
  5. 測試

2、配置流程

2.1 打開郵箱的POP三、SMTP

圖示

2.2 導入包

圖示

2.3 配置郵件發送類

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">

	<context:component-scan base-package="com.xkt"></context:component-scan>

	<!-- 配置郵件發送類 -->
	<bean name="mailSender"
		class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<!-- 指定郵件的編碼 -->
		<property name="defaultEncoding" value="UTF-8"></property>
		<!-- 指定郵件的服務器 -->
		<property name="host" value="smtp.qq.com"></property>
		<!-- 指定發送人的郵箱 -->
		<property name="username" value="這裏填入郵箱帳號"></property>
		<!-- 指定發送人的密碼 -->
		<property name="password" value="這裏填入郵箱受權的密碼"></property>
		<!-- 指定發送的郵箱服務器是需求認證的 -->
		<property name="javaMailProperties">
			<value>
				mail.smtp.auth=true
			</value>
		</property>
	</bean>
</beans>

2.4 郵件發送內容

package com.xkt.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;

/**
 * @author lzx
 *
 */
@Service
public class MailService {

	@Autowired
	private MailSender mailSender;

	/**
	 * 發送郵件
	 */
	public void send() {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setTo("這裏填入要發送到的郵箱");
		message.setText("Hello");
		message.setSubject("title");
		message.setFrom("******");
		message.setSentDate(new Date());

		mailSender.send(message);
	}

}

2.5 測試代碼

package com.xkt.test;

import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.xkt.service.MailService;

/**
 * @author lzx
 *
 */
public class MailServiceTest {

	@Test
	public void send() {
		try {
			ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
					"classpath:applicationContext.xml");
			MailService mailService = context.getBean(MailService.class);
			// 發送郵件
			mailService.send();
			context.close();
		} catch (BeansException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

版權說明:歡迎以任何方式進行轉載,但請在轉載後註明出處!spring

相關文章
相關標籤/搜索