使用JAVA发送邮件(smtp与Exchange两种协议)
一、SMTP协议发送邮件
老规矩,先贴代码
1.一个工具类
import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Component;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
@Component
public class SendEmailUtil {
private static String account = "登录用户名";//登录用户名
private static String pass = "登录密码"; //登录密码
private static String host = "smtp.exmail.qq.com"; //服务器地址(邮件服务器)
private static String port = "465"; //端口
private static String protocol = "smtp"; //协议
static class MyAuthenricator extends Authenticator {
String u;
String p;
public MyAuthenricator(String u,String p){
this.u=u;
this.p=p;
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(u,p);
public void send(String to, String subject, String content){
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", protocol);
//服务器
prop.setProperty("mail.smtp.host", host);
prop.setProperty("mail.smtp.port", port);
//使用smtp身份验证
prop.setProperty("mail.smtp.auth", "true");
//使用SSL,企业邮箱必需!
//开启安全协议
MailSSLSocketFactory sf = null;
try {
sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
} catch (GeneralSecurityException e1) {
e1.printStackTrace();
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass));
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
try {
//发件人
mimeMessage.setFrom(new InternetAddress(account,"XXX")); //可以设置发件人的别名
//mimeMessage.setFrom(new InternetAddress(account)); //如果不需要就省略
//收件人
mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
mimeMessage.setSubject(subject);
mimeMessage.setSentDate(new Date());
//容器类,可以包含多个MimeBodyPart对象
Multipart mp = new MimeMultipart();
//MimeBodyPart可以包装文本,图片,附件
MimeBodyPart body = new MimeBodyPart();
//HTML正文
body.setContent(content, "text/html; charset=UTF-8");
mp.addBodyPart(body);
//设置邮件内容
mimeMessage.setContent(mp);
//仅仅发送文本
//mimeMessage.setText(content);
mimeMessage.saveChanges();
Transport.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
这里面主要配置的是发件邮箱的账号,密码,还有服务器地址(邮箱服务器),我这边使用的是smtp.exmail.qq.com,还有端口号465以及邮箱协议smtp。
这些信息必须自己先登录过邮箱,验证下正确性,再填写上去测试,不然搞的一个错的账号密码,怎么可能成功。然后比如一些协议或者服务器地址不知道的话可以先用邮箱软件登录看下配置。可以用outlook,网易邮箱大师,我这边就给大家看下邮箱大师是怎么看的,如图:
public SendEmailUtil emailUtil;
private static String to = "发件邮箱地址";
private static String subject = "测试邮件标题";
private static String text = "测试邮件内容信息";
@GetMapping(path = "sendEmail")
public Boolean sendEmail(){
log.info("Sending!");
emailUtil.send(to, subject , text );
log.info("Done!");
return Boolean.TRUE;
这里就是调用1的组件发送邮箱。下面介绍下Exchange邮箱的发件配置
二、Exchange协议发送邮件
1.maven配置
<dependency>
<groupId>com.microsoft.ews-java-api</groupId>
<artifactId>ews-java-api</artifactId>
<version>2.0</version>
</dependency>
2.组件类
package com.neucloud.zhtest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.exception.service.local.ServiceLocalException;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
@Slf4j
public class ExchangeClient {
private final String hostname;
private final ExchangeVersion exchangeVersion;
private final String domain;
private final String username;
private final String password;
private final String subject;
private final String recipientTo;
private final List<String> recipientCc;
private final List<String> recipientBcc;
private final List<String> attachments;
private final String message;
private ExchangeClient(ExchangeClientBuilder builder) {
this.hostname = builder.hostname;
this.exchangeVersion = builder.exchangeVersion;
this.domain = builder.domain;
this.username = builder.username;
this.password = builder.password;
this.subject = builder.subject;
this.recipientTo = builder.recipientTo;
this.recipientCc = builder.recipientCc;
this.recipientBcc = builder.recipientBcc;
this.attachments = builder.attachments;
this.message = builder.message;
public static class ExchangeClientBuilder {
private String hostname;
private ExchangeVersion exchangeVersion;
private String domain;
private String username;
private String password;
private String subject;
private String recipientTo;
private List<String> recipientCc;
private List<String> recipientBcc;
private List<String> attachments;
private String message;
public ExchangeClientBuilder() {
this.exchangeVersion = ExchangeVersion.Exchange2010_SP1;
this.hostname = "";
this.username = "";
this.password = "";
this.subject = "";
this.recipientTo = "";
this.recipientCc = new ArrayList<>(0);
this.recipientBcc = new ArrayList<>(0);
this.attachments = new ArrayList<>(0);
this.message = "";
* The hostname of the Exchange Web Service. It will be used for
* connecting with URI https://hostname/ews/exchange.asmx
* @param hostname the hostname of the MS Exchange Smtp Server.
* @return the builder for chain usage.
public ExchangeClientBuilder hostname(String hostname) {
this.hostname = hostname;
return this;
* The Exchange Web Server version.
* @param exchangeVersion the Exchange Web Server version.
* @return the builder for chain usage.
public ExchangeClientBuilder exchangeVersion(ExchangeVersion exchangeVersion) {
this.exchangeVersion = exchangeVersion;
return this;
* The domain of the MS Exchange Smtp Server.
* @param domain the domain of the Active Directory. The first part of
* the username. For example: MYDOMAIN\\username, set the MYDOMAIN.
* @return the builder for chain usage.
public ExchangeClientBuilder domain(String domain) {
this.domain = domain;
return this;
* The username of the MS Exchange Smtp Server. The second part of the
* username. For example: MYDOMAIN\\username, set the username.
* @param username the username of the MS Exchange Smtp Server.
* @return the builder for chain usage.
public ExchangeClientBuilder username(String username) {
this.username = username;
return this;
* The password of the MS Exchange Smtp Server.
* @param password the password of the MS Exchange Smtp Server.
* @return the builder for chain usage.
public ExchangeClientBuilder password(String password) {
this.password = password;
return this;
* The subject for this send.
* @param subject the subject for this send.
* @return the builder for chain usage.
public ExchangeClientBuilder subject(String subject) {
this.subject = subject;
return this;
* The recipient for this send.
* @param recipientTo the recipient for this send.
* @return the builder for chain usage.
public ExchangeClientBuilder recipientTo(String recipientTo) {
this.recipientTo = recipientTo;
return this;
* You can specify one or more email address that will be used as cc
* recipients.
* @param recipientCc the first cc email address.
* @param recipientsCc the other cc email address for this send.
* @return the builder for chain usage.
public ExchangeClientBuilder recipientCc(String recipientCc, String... recipientsCc) {
// Prepare the list.
List<String> recipients = new ArrayList<>(1 + recipientsCc.length);
recipients.add(recipientCc);
recipients.addAll(Arrays.asList(recipientsCc));
// Set the list.
this.recipientCc = recipients;
return this;
* You can specify a list with email addresses that will be used as cc
* for this email send.
* @param recipientCc the list with email addresses that will be used as
* cc for this email send.
* @return the builder for chain usage.
public ExchangeClientBuilder recipientCc(List<String> recipientCc) {
this.recipientCc = recipientCc;
return this;
* You can specify one or more email address that will be used as bcc
* recipients.
* @param recipientBcc the first bcc email address.
* @param recipientsBcc the other bcc email address for this send.
* @return the builder for chain usage.
public ExchangeClientBuilder recipientBcc(String recipientBcc, String... recipientsBcc) {
// Prepare the list.
List<String> recipients = new ArrayList<>(1 + recipientsBcc.length);
recipients.add(recipientBcc);
recipients.addAll(Arrays.asList(recipientsBcc));
// Set the list.
this.recipientBcc = recipients;
return this;
* You can specify a list with email addresses that will be used as bcc
* for this email send.
* @param recipientBcc the list with email addresses that will be used
* as bcc for this email send.
* @return the builder for chain usage.
public ExchangeClientBuilder recipientBcc(List<String> recipientBcc) {
this.recipientBcc = recipientBcc;
return this;
* You can specify one or more email address that will be used as cc
* recipients.
* @param attachment the first attachment.
* @param attachments the other attachments for this send.
* @return the builder for chain usage.
public ExchangeClientBuilder attachments(String attachment, String... attachments) {
// Prepare the list.
List<String> attachmentsToUse = new ArrayList<>(1 + attachments.length);
attachmentsToUse.add(attachment);
attachmentsToUse.addAll(Arrays.asList(attachments));
// Set the list.
this.attachments = attachmentsToUse;
return this;
* You can specify a list with email attachments that will be used for
* this email send.
* @param attachments the list with email attachments that will be used
* for this email send.
* @return the builder for chain usage.
public ExchangeClientBuilder attachments(List<String> attachments) {
this.attachments = attachments;
return this;
* The body of the email message.
* @param message the body of the email message.
* @return the builder for chain usage.
public ExchangeClientBuilder message(String message) {
this.message = message;
return this;
* Build a mail.
* @return an EmailApacheUtils object.
public ExchangeClient build() {
return new ExchangeClient(this);
public boolean sendExchange() {
// The Exchange Server Version.
ExchangeService exchangeService = new ExchangeService(exchangeVersion);
// Credentials to sign in the MS Exchange Server.
ExchangeCredentials exchangeCredentials = new WebCredentials(username, password, domain);
exchangeService.setCredentials(exchangeCredentials);
// URL of exchange web service for the mailbox.
try {
exchangeService.setUrl(new URI("https://" + hostname + "/ews/Exchange.asmx"));
} catch (URISyntaxException ex) {
log.info("An exception occured while creating the uri for exchange service.", ex);
return false;
// The email.
EmailMessage emailMessage;
try {
emailMessage = new EmailMessage(exchangeService);
emailMessage.setSubject(subject);
emailMessage.setBody(MessageBody.getMessageBodyFromText(message));
} catch (Exception ex) {
log.info("An exception occured while setting the email message.", ex);
return false;
// TO recipient.
try {
emailMessage.getToRecipients().add(recipientTo);
} catch (ServiceLocalException ex) {
log.info("An exception occured while sstting the TO recipient(" + recipientTo + ").", ex);
return false;
// CC recipient.
for (String recipient : recipientCc) {
try {
emailMessage.getCcRecipients().add(recipient);
} catch (ServiceLocalException ex) {
log.info("An exception occured while sstting the CC recipient(" + recipient + ").", ex);
return false;
// BCC recipient
for (String recipient : recipientBcc) {
try {
emailMessage.getBccRecipients().add(recipient);
} catch (ServiceLocalException ex) {
log.info("An exception occured while sstting the BCC recipient(" + recipient + ").", ex);
return false;
// Attachements.
for (String attachmentPath : attachments) {
try {
emailMessage.getAttachments().addFileAttachment(attachmentPath);
} catch (ServiceLocalException ex) {
log.info("An exception occured while setting the attachment.", ex);
return false;
try {
emailMessage.send();
log.info("An email is send.");
} catch (Exception ex) {
log.info("An exception occured while sending an email.", ex);
return false;
return true;
import lombok.extern.slf4j.Slf4j;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/email")
public class EmailController {
@Autowired
public SendEmailUtil emailUtil;
private static String account = "邮箱账户";
private static String pass = "密码";
private static String host = "邮箱服务器地址";
@GetMapping(path = "sendEmail")
public Boolean sendEmail(){
log.info("Sending!");
ExchangeClient client = new ExchangeClient.ExchangeClientBuilder()
.hostname(host)
.exchangeVersion(ExchangeVersion.Exchange2010)
.username(account)
.password(pass)
.recipientTo(发送邮箱地址)
.subject("Test Subject")
.message("Test Message")
.build();
client.sendExchange();
log.info("Done!");
return Boolean.TRUE;
有问题请评论,我会及时回复