java 实现邮箱发送邮件功能(端口:465、587)

使用465端口对邮件进行ssl加密传输

package com.example.alysslEmail;

import java.security.Security;

import java.util.Date;

import java.util.Properties;

import javax.mail.Authenticator;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

/**

* javaMail的邮件工具类

* @author wangXgnaw

*

*/

public class MailUtil {

public static void main(String[] args) {

sendEmil("[email protected]", "邮件发送测试,成功!!"); 

}

/**

* 使用加密的方式,利用465端口进行传输邮件,开启ssl

* @param to 为收件人邮箱

* @param message 发送的消息

*/

public static void sendEmil(String to, String message) {

try {

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

//设置邮件会话参数

Properties props = new Properties();

//邮箱的发送服务器地址

props.setProperty("mail.smtp.host", "smtp.hkvastnet.com");

props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);

props.setProperty("mail.smtp.socketFactory.fallback", "false");

//邮箱发送服务器端口,这里设置为465端口

props.setProperty("mail.smtp.port", "465");

props.setProperty("mail.smtp.socketFactory.port", "465");

props.put("mail.smtp.auth", "true");

final String username = "[email protected]"; //发送者邮箱用户名

final String password = "Btkj@2018"; //发送者邮箱密码或者邮箱授权码

//获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm

Session session = Session.getDefaultInstance(props, new Authenticator() {

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);

}

});

//通过会话,得到一个邮件,用于发送

Message msg = new MimeMessage(session);

//设置发件人

msg.setFrom(new InternetAddress("[email protected]")); //发件人邮箱

//设置收件人,to为收件人,cc为抄送,bcc为密送

msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(to, false));

msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(to, false));

msg.setSubject("邮件主题");

//设置邮件消息

msg.setText(message);

//设置发送的日期

msg.setSentDate(new Date());

//调用Transport的send方法去发送邮件

Transport.send(msg);

} catch (Exception e) {

e.printStackTrace();

}

}

}

使用465端口对邮件进行ssl加密传输 --- 带附件

package com.example.alysslEmail;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.Date;

import java.util.List;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Address;

import javax.mail.BodyPart;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import javax.mail.internet.MimeUtility;

public class SendMailBySSL {

private final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

private String smtpServer; // SMTP服务器地址

private String port; // 端口

private String username; // 登录SMTP服务器的用户名

private String password; // 登录SMTP服务器的密码

private List<String> recipients = new ArrayList<String>(); // 收件人地址集合

private String subject; // 邮件主题

private String content; // 邮件正文

private List<String> attachmentNames = new ArrayList<String>(); // 附件路径信息集合

public SendMailBySSL() {

}

public SendMailBySSL(String smtpServer, String port, String username,

String password, List<String> recipients, String subject,

String content, List<String> attachmentNames) {

this.smtpServer = smtpServer;

this.port = port;

this.username = username;

this.password = password;

this.recipients = recipients;

this.subject = subject;

this.content = content;

this.attachmentNames = attachmentNames;

}

public void setSmtpServer(String smtpServer) {

this.smtpServer = smtpServer;

}

public void setPort(String port) {

this.port = port;

}

public void setUsername(String username) {

this.username = username;

}

public void setPassword(String password) {

this.password = password;

}

public void setRecipients(List<String> recipients) {

this.recipients = recipients;

}

public void setSubject(String subject) {

this.subject = subject;

}

public void setContent(String content) {

this.content = content;

}

public void setAttachmentNames(List<String> attachmentNames) {

this.attachmentNames = attachmentNames;

}

/**

* 进行base64加密,防止中文乱码

* */

public String changeEncode(String str) {

try {

str = MimeUtility.encodeText(new String(str.getBytes(), "UTF-8"),

"UTF-8", "B"); // "B"代表Base64

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

return str;

}

/**

* 正式发邮件

* */

public boolean sendMail() {

Properties properties = new Properties();

properties.put("mail.smtp.host", smtpServer);

properties.put("mail.smtp.auth", "true");

properties.put("mail.smtp.socketFactory.class", SSL_FACTORY); //使用JSSE的SSL socketfactory来取代默认的socketfactory

properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理

properties.put("mail.smtp.port", port);

properties.put("mail.smtp.socketFactory.port", port);

Session session = Session.getInstance(properties);

session.setDebug(true);

MimeMessage message = new MimeMessage(session);

try {

// 发件人

Address address = new InternetAddress(username);

message.setFrom(address);

// 收件人

for (String recipient : recipients) {

System.out.println("收件人:" + recipient);

Address toAddress = new InternetAddress(recipient);

message.setRecipient(MimeMessage.RecipientType.TO, toAddress); // 设置收件人,并设置其接收类型为TO 发送单个

// message.addRecipient(MimeMessage.RecipientType.TO, toAddress); //发送多个,

/**

* TO:代表有健的主要接收者。 CC:代表有健的抄送接收者。 BCC:代表邮件的暗送接收者。

* */

}

// 主题

message.setSubject(changeEncode(subject));

// 时间

message.setSentDate(new Date());

Multipart multipart = new MimeMultipart();

// 添加文本

BodyPart text = new MimeBodyPart();

text.setText(content);

multipart.addBodyPart(text);

// 添加附件

for (String fileName : attachmentNames) {

BodyPart adjunct = new MimeBodyPart();

FileDataSource fileDataSource = new FileDataSource(fileName);

adjunct.setDataHandler(new DataHandler(fileDataSource));

adjunct.setFileName(changeEncode(fileDataSource.getName()));

multipart.addBodyPart(adjunct);

}

// 清空收件人集合,附件集合

recipients.clear();

attachmentNames.clear();

message.setContent(multipart);

message.saveChanges();

} catch (Exception e) {

e.printStackTrace();

return false;

}

try {

Transport transport = session.getTransport("smtp");

transport.connect(smtpServer, username, password);

transport.sendMessage(message, message.getAllRecipients());

transport.close();

} catch (Exception e) {

e.printStackTrace();

return false;

}

return true;

}

public static void main(String[] args) {

List<String> recipients = new ArrayList<String>();

// recipients.add("[email protected]");

recipients.add("[email protected]"); //收件人

String subject = "这封邮件是为了测试SMTP的SSL加密传输";

String content = "这是这封邮件的正文";

List<String> attachmentNames = new ArrayList<String>();

attachmentNames.add("C://Users//48732//Desktop//新建文本文档 (2).txt");

SendMailBySSL sendMailBySSL = new SendMailBySSL("smtp.hkvastnet.com", "465",

"[email protected]", "Btkj@2018", recipients, subject, content,

attachmentNames);

sendMailBySSL.sendMail();

}

}

使用587端口对邮件进行ssl加密传输

package com.example;

import java.io.File;

import java.util.Properties;

import javax.mail.MessagingException;

import javax.mail.internet.MimeMessage;

import org.springframework.core.io.FileSystemResource;

import org.springframework.mail.MailException;

import org.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSenderImpl;

import org.springframework.mail.javamail.MimeMessageHelper;

public class MailUtil {

private static final String HOST = "smtp.qq.com";

private static final String SMTP = "smtp";

private static final String USERNAME = "[email protected]"; //发送者

private static final String PASSWORD = "rnwasrxlaxepdccb";

private static final int PORT = 587;//587/465

private static final String DEFAULTENCODING = "UTF-8";

private static final String RECEIVEUSERNAME="[email protected]"; //收件人

private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

private static Properties prop = new Properties();

static{

// 设定mail server

senderImpl.setHost(HOST);

senderImpl.setProtocol(SMTP);

senderImpl.setUsername(USERNAME);

senderImpl.setPassword(PASSWORD);

senderImpl.setPort(PORT);

senderImpl.setDefaultEncoding(DEFAULTENCODING);

// 设定properties

prop.put("mail.smtp.auth", "true");

prop.put("mail.smtp.timeout", "90000");

//设置调试模式可以在控制台查看发送过程

prop.put("mail.debug", "true");

senderImpl.setJavaMailProperties(prop);

}

public static void main(String args[]) {

// 设置收件人,寄件人 用数组发送多个邮件

// String[] array = new String[] {"[email protected]","[email protected]","[email protected]",USERNAME};

/**

* array 收件人数组 群发邮件时,使用数组多次发送

*/

String[] array = new String[] {RECEIVEUSERNAME};

String subject = "Cherish内嵌图片、音乐的邮件";

// StringBuffer sb = new StringBuffer();

// try {

// URL url = new URL("http://www.imooc.com/");//http://android-studio.org/

//

// URLConnection conn = url.openConnection();

// InputStream is = conn.getInputStream();

//

// BufferedReader reader = new BufferedReader(new InputStreamReader(is));

//

// String string = null;

// while ((string = reader.readLine()) != null) {

// sb.append(string);

// }

//

// //System.out.println(sb.toString());

//

// } catch (Exception e) {

// e.printStackTrace();

// }

//

// boolean result = htmlMail(array, subject, sb.toString());

String filePath = "C:/Users/48732/Desktop/bq.png";

String html = "<html><head>"+

"</head><body>"+

"<audio src='http://m10.music.126.net/20160422225433/25b43b999bcdaf3425b9194514340596/ymusic/8c94/b9af/69e3/7ebe35b8e00154120822550b21b0c9c5.mp3' autoplay='autoplay' controls='controls' loop='-1'>测试</audio>"+

"<h1>Hello,Nice to meet you!</h1>"+

"<span style='color:red;font-size:20px;'>发送邮件成功!!!</span>"+

"<img src='cid:javaxmail.png'>"+

"</body></html>";

boolean result = inlineFileMail(array, subject, html, filePath);

// boolean result = singleMail(RECEIVEUSERNAME, "主题", "内容");

if (result) {

System.out.println("发送邮件成功。。。。");

}

}

/**

* 发送简单邮件

* @param to 收件人邮箱

* @param subject 主题

* @param content 内容

* @return

*/

public static boolean singleMail(String to, String subject, String content){

String[] array = new String[] {to};

return singleMail(array, subject, content);

}

/**

* 发送简单文本邮件

* @param to 收件人邮箱数组

* @param subject 主题

* @param content 内容

* @return

*/

public static boolean singleMail(String[] to, String subject, String content){

boolean result = true;

SimpleMailMessage mailMessage = new SimpleMailMessage();

// 设置收件人,寄件人 用数组发送多个邮件

mailMessage.setTo(to);

mailMessage.setFrom(USERNAME); //发件人

mailMessage.setSubject(subject);

mailMessage.setText(content);

// 发送邮件

try {

senderImpl.send(mailMessage);

} catch (MailException e) {

e.printStackTrace();

result = false;

}

return result;

}

/**

* 发送html邮件

* @param to 收件人

* @param subject 主题

* @param html html代码

* @return

*/

public static boolean htmlMail(String[] to, String subject, String html){

boolean result = true;

MimeMessage mailMessage = senderImpl.createMimeMessage();

MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);

try {

// 设置收件人,寄件人 用数组发送多个邮件

messageHelper.setTo(to);

messageHelper.setFrom(USERNAME);

messageHelper.setSubject(subject);

// true 表示启动HTML格式的邮件

messageHelper.setText(html, true);

// 发送邮件

senderImpl.send(mailMessage);

} catch (MessagingException e) {

result = false;

e.printStackTrace();

}

return result;

}

/**

* 发送内嵌图片的邮件 (cid:资源名)

* @param to 收件人邮箱

* @param subject 主题

* @param html html代码

* @param imgPath 图片路径

* @return

*/

public static boolean inlineFileMail(String[] to, String subject, String html, String filePath){

boolean result = true;

MimeMessage mailMessage = senderImpl.createMimeMessage();

try {

//设置true开启嵌入图片的功能

MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);

// 设置收件人,寄件人 用数组发送多个邮件

messageHelper.setTo(to);

messageHelper.setFrom(USERNAME);

messageHelper.setSubject(subject);

// true 表示启动HTML格式的邮件

messageHelper.setText(html, true);

FileSystemResource file = new FileSystemResource(new File(filePath));

messageHelper.addInline(file.getFilename(), file);

// 发送邮件

senderImpl.send(mailMessage);

} catch (MessagingException e) {

result = false;

e.printStackTrace();

}

return result;

}

/**

* 发送带附件的邮件

* @param to

* @param subject

* @param html

* @param filePath

* @return

*/

public static boolean attachedFileMail(String[] to, String subject, String html, String filePath){

boolean result = true;

MimeMessage mailMessage = senderImpl.createMimeMessage();

try {

// multipart模式 为true时发送附件 可以设置html格式

MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");

// 设置收件人,寄件人 用数组发送多个邮件

messageHelper.setTo(to);

messageHelper.setFrom(USERNAME);

messageHelper.setSubject(subject);

// true 表示启动HTML格式的邮件

messageHelper.setText(html, true);

FileSystemResource file = new FileSystemResource(new File(filePath));

// 这里的方法调用和插入图片是不同的。

messageHelper.addAttachment(file.getFilename(), file);

// 发送邮件

senderImpl.send(mailMessage);

} catch (MessagingException e) {

result = false;

e.printStackTrace();

}

return result;

}

}

猜你喜欢

转载自blog.csdn.net/weixin_41796611/article/details/81907083