使用 java发送邮件
最近在做安全测试这一块,其中有几条告警邮件的提测,用到了java发送邮件,所以,
邮件发送实体类 EmailEntity
package com.bkt.zcqsm.reshandover.entity;
public class EmailEntity {
//主题
public String theme;
//邮件内容
public String content;
//邮件发送者
public String senderToMail;
//邮件接受者
public String recipientsOfMail;
public EmailEntity(String theme,String content,String senderToMail,String recipientsOfMail) {
this.theme = theme;
this.content = content;
this.senderToMail = senderToMail;
this.recipientsOfMail = recipientsOfMail;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getSenderToMail() {
return senderToMail;
}
public void setSenderToMail(String senderToMail) {
this.senderToMail = senderToMail;
}
public String getRecipientsOfMail() {
return recipientsOfMail;
}
public void setRecipientsOfMail(String recipientsOfMail) {
this.recipientsOfMail = recipientsOfMail;
}
}
是否启用ssl 加密的方法。这个是完好的代码,不必动它,直接粘贴使用
package com.bkt.zcqsm.reshandover.util;
import java.io.*;
import java.net.*;
import java.security.*;
import java.security.cert.*;
import java.util.*;
import javax.net.ssl.*;
public class MailSSLSocketFactory extends SSLSocketFactory {
/** Should all hosts be trusted? */
private boolean trustAllHosts;
/** String-array of trusted hosts */
private String[] trustedHosts = null;
/** Holds a SSLContext to get SSLSocketFactories from */
private SSLContext sslcontext;
/** Holds the KeyManager array to use */
private KeyManager[] keyManagers;
/** Holds the TrustManager array to use */
private TrustManager[] trustManagers;
/** Holds the SecureRandom to use */
private SecureRandom secureRandom;
/** Holds a SSLSocketFactory to pass all API-method-calls to */
private SSLSocketFactory adapteeFactory = null;
/**
* Initializes a new MailSSLSocketFactory.
*
* @throws GeneralSecurityException for security errors
*/
public MailSSLSocketFactory() throws GeneralSecurityException {
this("TLS");
}
/**
* Initializes a new MailSSLSocketFactory with a given protocol.
* Normally the protocol will be specified as "TLS".
*
* @param protocol The protocol to use
* @throws NoSuchAlgorithmException if given protocol is not supported
* @throws GeneralSecurityException for security errors
*/
public MailSSLSocketFactory(String protocol)
throws GeneralSecurityException {
// By default we do NOT trust all hosts.
trustAllHosts = false;
// Get an instance of an SSLContext.
sslcontext = SSLContext.getInstance(protocol);
// Default properties to init the SSLContext
keyManagers = null;
trustManagers = new TrustManager[] { new MailTrustManager() };
secureRandom = null;
// Assemble a default SSLSocketFactory to delegate all API-calls to.
newAdapteeFactory();
}
/**
* Gets an SSLSocketFactory based on the given (or default)
* KeyManager array, TrustManager array and SecureRandom and
* sets it to the instance var adapteeFactory.
*
* @throws KeyManagementException for key manager errors
*/
private synchronized void newAdapteeFactory()
throws KeyManagementException {
sslcontext.init(keyManagers, trustManagers, secureRandom);
// Get SocketFactory and save it in our instance var
adapteeFactory = sslcontext.getSocketFactory();
}
/**
* @return the keyManagers
*/
public synchronized KeyManager[] getKeyManagers() {
return keyManagers.clone();
}
/**
* @param keyManagers the keyManagers to set
* @throws GeneralSecurityException for security errors
*/
public synchronized void setKeyManagers(KeyManager[] keyManagers)
throws GeneralSecurityException {
this.keyManagers = keyManagers.clone();
newAdapteeFactory();
}
/**
* @return the secureRandom
*/
public synchronized SecureRandom getSecureRandom() {
return secureRandom;
}
/**
* @param secureRandom the secureRandom to set
* @throws GeneralSecurityException for security errors
*/
public synchronized void setSecureRandom(SecureRandom secureRandom)
throws GeneralSecurityException {
this.secureRandom = secureRandom;
newAdapteeFactory();
}
/**
* @return the trustManagers
*/
public synchronized TrustManager[] getTrustManagers() {
return trustManagers;
}
/**
* @param trustManagers the trustManagers to set
* @throws GeneralSecurityException for security errors
*/
public synchronized void setTrustManagers(TrustManager[] trustManagers)
throws GeneralSecurityException {
this.trustManagers = trustManagers;
newAdapteeFactory();
}
/**
* @return true if all hosts should be trusted
*/
public synchronized boolean isTrustAllHosts() {
return trustAllHosts;
}
/**
* @param trustAllHosts should all hosts be trusted?
*/
public synchronized void setTrustAllHosts(boolean trustAllHosts) {
this.trustAllHosts = trustAllHosts;
}
/**
* @return the trusted hosts
*/
public synchronized String[] getTrustedHosts() {
if (trustedHosts == null)
return null;
else
return trustedHosts.clone();
}
/**
* @param trustedHosts the hosts to trust
*/
public synchronized void setTrustedHosts(String[] trustedHosts) {
if (trustedHosts == null)
this.trustedHosts = null;
else
this.trustedHosts = trustedHosts.clone();
}
/**
* After a successful conection to the server, this method is
* called to ensure that the server should be trusted.
*
* @param server name of the server we connected to
* @param sslSocket SSLSocket connected to the server
* @return true if "trustAllHosts" is set to true OR the server
* is contained in the "trustedHosts" array;
*/
public synchronized boolean isServerTrusted(String server,
SSLSocket sslSocket) {
//System.out.println("DEBUG: isServerTrusted host " + server);
// If "trustAllHosts" is set to true, we return true
if (trustAllHosts)
return true;
// If the socket host is contained in the "trustedHosts" array,
// we return true
if (trustedHosts != null)
return Arrays.asList(trustedHosts).contains(server); // ignore case?
// If we get here, trust of the server was verified by the trust manager
return true;
}
// SocketFactory methods
/* (non-Javadoc)
* @see javax.net.ssl.SSLSocketFactory#createSocket(java.net.Socket,
* java.lang.String, int, boolean)
*/
@Override
public synchronized Socket createSocket(Socket socket, String s, int i,
boolean flag) throws IOException {
return adapteeFactory.createSocket(socket, s, i, flag);
}
/* (non-Javadoc)
* @see javax.net.ssl.SSLSocketFactory#getDefaultCipherSuites()
*/
@Override
public synchronized String[] getDefaultCipherSuites() {
return adapteeFactory.getDefaultCipherSuites();
}
/* (non-Javadoc)
* @see javax.net.ssl.SSLSocketFactory#getSupportedCipherSuites()
*/
@Override
public synchronized String[] getSupportedCipherSuites() {
return adapteeFactory.getSupportedCipherSuites();
}
/* (non-Javadoc)
* @see javax.net.SocketFactory#createSocket()
*/
@Override
public synchronized Socket createSocket() throws IOException {
return adapteeFactory.createSocket();
}
/* (non-Javadoc)
* @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int,
* java.net.InetAddress, int)
*/
@Override
public synchronized Socket createSocket(InetAddress inetaddress, int i,
InetAddress inetaddress1, int j) throws IOException {
return adapteeFactory.createSocket(inetaddress, i, inetaddress1, j);
}
/* (non-Javadoc)
* @see javax.net.SocketFactory#createSocket(java.net.InetAddress, int)
*/
@Override
public synchronized Socket createSocket(InetAddress inetaddress, int i)
throws IOException {
return adapteeFactory.createSocket(inetaddress, i);
}
/* (non-Javadoc)
* @see javax.net.SocketFactory#createSocket(java.lang.String, int,
* java.net.InetAddress, int)
*/
@Override
public synchronized Socket createSocket(String s, int i,
InetAddress inetaddress, int j)
throws IOException, UnknownHostException {
return adapteeFactory.createSocket(s, i, inetaddress, j);
}
/* (non-Javadoc)
* @see javax.net.SocketFactory#createSocket(java.lang.String, int)
*/
@Override
public synchronized Socket createSocket(String s, int i)
throws IOException, UnknownHostException {
return adapteeFactory.createSocket(s, i);
}
// inner classes
/**
* A default Trustmanager.
*
* @author Stephan Sann
*/
private class MailTrustManager implements X509TrustManager {
/** A TrustManager to pass method calls to */
private X509TrustManager adapteeTrustManager = null;
/**
* Initializes a new TrustManager instance.
*/
private MailTrustManager() throws GeneralSecurityException {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init((KeyStore)null);
adapteeTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
}
/* (non-Javadoc)
* @see javax.net.ssl.X509TrustManager#checkClientTrusted(
* java.security.cert.X509Certificate[], java.lang.String)
*/
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
if (!(isTrustAllHosts() || getTrustedHosts() != null))
adapteeTrustManager.checkClientTrusted(certs, authType);
}
/* (non-Javadoc)
* @see javax.net.ssl.X509TrustManager#checkServerTrusted(
* java.security.cert.X509Certificate[], java.lang.String)
*/
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType)
throws CertificateException {
if (!(isTrustAllHosts() || getTrustedHosts() != null))
adapteeTrustManager.checkServerTrusted(certs, authType);
}
/* (non-Javadoc)
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return adapteeTrustManager.getAcceptedIssuers();
}
}
}
邮件发送实现方法
package com.bkt.zcqsm.reshandover.util;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import com.bkt.zcqsm.reshandover.entity.EmailEntity;
public class EmailServiceImpl {
@Autowired
private Environment env;
public void sendEmail(EmailEntity emailEntity) throws Exception {
Properties prop = new Properties();
// 设置QQ邮件服务器
prop.setProperty("mail.host", env.getProperty("emailserver.emailService"));
// 邮件发送协议
prop.setProperty("mail.transport.protocol", env.getProperty("emailserver.emailType"));
// 需要验证用户名密码
prop.setProperty("mail.smtp.auth", env.getProperty("emailserver.emailAutName"));
// 关于邮箱,还要设置SSL加密,加上以下代码即可
if ("true".equals(env.getProperty("emailserver.enableSSL"))) {
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable", "true");
prop.put("mail.smtp.ssl.socketFactory", sf);
}
//使用JavaMail发送邮件的5个步骤
//创建定义整个应用程序所需的环境信息的 Session 对象
Session session = Session.getDefaultInstance(prop, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//发件人邮件用户名、授权码
return new PasswordAuthentication(env.getProperty("emailserver.emailAutName"), env.getProperty("emailserver.emailLoginPwd"));
}
});
//开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
session.setDebug(true);
//2、通过session得到transport对象
Transport ts = session.getTransport();
//3、使用邮箱的用户名和授权码连上邮件服务器
ts.connect(env.getProperty("emailserver.emailService"), env.getProperty("emailserver.emailAutName"), env.getProperty("emailserver.emailLoginPwd"));
//4、创建邮件
//创建邮件对象
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(emailEntity.getSenderToMail()));
//指明邮件的收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailEntity.getRecipientsOfMail()));
//邮件的标题
message.setSubject(emailEntity.getTheme());
//邮件的文本内容
message.setContent(emailEntity.getContent(), "text/html;charset=UTF-8");
//5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
}
配置一些信息。 在EmailServiceImpl这个类里面使用到
#email
emailserver:
emailService: smtp.qq.com
emailType: smtp
emailAutName: true
emailLoginName: 601967321@qq.com
emailLoginPwd: qtoezfylftmbbcbidjj
enableSSL: true
写一个main方法,使用
package com.bkt.zcqsm.util;
import com.bkt.zcqsm.reshandover.entity.EmailEntity;
import com.bkt.zcqsm.reshandover.util.EmailServiceImplTest;
public class EmailTest {
public static void main(String[] args) throws Exception {
EmailEntity emailEntity =new EmailEntity ("邮箱测试主题","邮箱测试内容","601967321@qq.com","601967321@qq.com");
EmailServiceImplTest emailimpl=new EmailServiceImplTest();
emailimpl.sendEmail(emailEntity);
}
}
这个方法是测试过的可以使用。