Java发送邮件工具类

调用smtp发送邮件所需要的jar包

<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>javax.mail-api</artifactId>
			<version>1.4.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-email</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<version>1.5.2</version>
		</dependency>
		<dependency>
			<groupId>commons-beanutils</groupId>
			<artifactId>commons-beanutils</artifactId>
			<version>1.8.3</version>
		</dependency>

package main.webapp;

import java.util.Date;
import java.util.List;
import java.util.Properties;
 


import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class SimpleMailSender {	
	public static void main(String[] args) throws AddressException, MessagingException{
        try{
            Properties props=new Properties();
            props.put("mail.smtp.host","smtp.qq.com");//QQ邮箱的smtp
            props.put("mail.smtp.auth", "true");
            Session mailSession = Session.getInstance(props);
                           
            //设置session,和邮件服务器进行通讯。
            mailSession.setDebug(true);
            MimeMessage message = new MimeMessage(mailSession);
            message.setSubject("java test"); // 设置邮件主题
            message.setText("java test"); // 设置邮件正文
//            message.setHeader("mail_head_name", "mail_head_value"); // 设置邮件标题
             
            message.setSentDate(new Date()); // 设置邮件发送日期
            InternetAddress address = new InternetAddress("[email protected]", "XXX");//QQ邮箱,昵称
            message.setFrom(address); // 设置邮件发送者的地址
            InternetAddress toAddress = new InternetAddress("[email protected]"); // 设置邮件接收方的地址
            message.addRecipient(Message.RecipientType.TO, toAddress);
            Transport transport = null;
            transport = mailSession.getTransport("smtp");
            
            message.saveChanges();
            transport.connect("smtp.qq.com", "[email protected]", "123456");//smtp地址,qq邮箱,邮箱密码
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            
            System.out.println("send success!");
        }catch (Exception ex){
            ex.printStackTrace();
        }
		
	}


}

若用QQ邮箱测试请开通QQ的smtp服务

你可能感兴趣的:(java,email)