- 邮箱stmp设置
- 选择开启stmp服务
- 注意保存授权密码
- 导包
<!--邮件发送-->
<!-- https://mvnrepository.com/artifact/com.sun.mail/javax.mail -->
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.6</version>
</dependency>
<!--Base64-->
<!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
1. 发送消息
- Base64加密Util
import org.apache.commons.codec.binary.Base64;
public class Base64Util {
/*
*加密
*/
public static String EncodeBase64(byte[] data) {
Base64 eb = new Base64();
return eb.encodeBase64String(data);
}
/*
*解密
*/
public static String DecodeBase64(String str) {
Base64 ba = new Base64();
byte[] ResultBase=ba.decodeBase64(str);
return new String(ResultBase);
}
}
- 发送测试
import java.io.*;
import java.net.Socket;
public class Test1 {
public static void main(String[] args) {
/*
*用户名和密码
*/
String SendUser = " @163.com";//发送邮箱
String SendPassword = " ";//授权密码,不是真实的邮箱密码
String ReceiveUser = " @163.com";//收件邮箱
/*
*对用户名和密码进行Base64编码
*/
String UserBase64 = Base64Util.EncodeBase64(SendUser.getBytes());
String PasswordBase64 = Base64Util.EncodeBase64(SendPassword.getBytes());
try {
/*
*远程连接smtp.163.com服务器的25号端口
*并定义输入流和输出流(输入流读取服务器返回的信息、输出流向服务器发送相应的信息)
*/
Socket socket = new Socket("smtp.163.com", 25);
InputStream inputStream = socket.getInputStream();//读取服务器返回信息的流
InputStreamReader isr = new InputStreamReader(inputStream);//字节解码为字符
BufferedReader br = new BufferedReader(isr);//字符缓冲
OutputStream outputStream = socket.getOutputStream();//向服务器发送相应信息
PrintWriter pw = new PrintWriter(outputStream, true);//true代表自带flush
System.out.println(br.readLine());
/*
*向服务器发送信息以及返回其相应结果
*/
//helo
pw.println("helo world!");
System.out.println(br.readLine());
//auth login
pw.println("auth login");
System.out.println(br.readLine());
pw.println(UserBase64);
System.out.println(br.readLine());
pw.println(PasswordBase64);
System.out.println(br.readLine());
pw.println("mail from:<" + SendUser + ">");
System.out.println(br.readLine());
pw.println("rcpt to:<" + ReceiveUser + ">");
System.out.println(br.readLine());
pw.println("data");
System.out.println(br.readLine());
//正文主体(包括标题,发送方,接收方,内容,点)
pw.println("subject:测试邮件");
pw.println("from:" + SendUser);
pw.println("to:" + ReceiveUser);
pw.println("Content-Type: text/plain;charset=\"utf-8\"");//设置编码格式可发送中文内容
pw.println();
pw.println("大家好,测试邮件!请勿回复");
pw.println(".");
pw.print("");
System.out.println(br.readLine());
/*
*发送完毕,中断与服务器连接
*/
pw.println("rset");
System.out.println(br.readLine());
pw.println("quit");
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 发送附件
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
public class Email {
//初始化参数
private static Properties prop;
private static String userEmail = "";//邮箱
private static String password = "";//授权密码
// 发件人
private static InternetAddress sendMan = null;
static {
prop = new Properties();
prop.put("mail.transport.protocol", "smtp"); // 协议
prop.put("mail.smtp.host", "smtp.163.com"); // 主机
//prop.put("mail.smtp.port", "25"); // 默认端口
prop.put("mail.smtp.auth", "true"); // 用户密码认证
//邮箱发送服务器端口,这里设置为465端口
prop.setProperty("mail.smtp.port", "465");
prop.put("mail.smtp.ssl.enable", "true");
prop.setProperty("mail.smtp.socketFactory.port", "465");
prop.put("mail.debug", "true"); // 调试模式
try {
sendMan = new InternetAddress(userEmail);
} catch (AddressException e) {
throw new RuntimeException(e);
}
}
//sendEmail传入收件人邮箱
public static void sendEmil(String title,String sendEmail,Date sentDate,String textContent,List<String> Email_File) throws Exception {
// 1. 创建邮件会话
Session session = Session.getDefaultInstance(prop);
// 2. 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 3. 设置参数:标题、发件人、收件人、发送时间、内容
message.setSubject(title);
message.setSender(sendMan);
message.setRecipient(RecipientType.TO, new InternetAddress(sendEmail));
message.setSentDate(sentDate);
// 构建一个总的邮件块
MimeMultipart mixed = new MimeMultipart("mixed");
// ---> 总邮件快,设置到邮件对象中
message.setContent(mixed);
// 左侧: (文本+图片资源)
MimeBodyPart left = new MimeBodyPart();
// 设置到总邮件块
mixed.addBodyPart(left);
/****** 附件 ********/
if(Email_File!=null && Email_File.size()>0){
// 右侧: 附件
for (String string : Email_File) {
MimeBodyPart right = new MimeBodyPart();
String attr_path = string;
DataSource attr_ds = new FileDataSource(new File(attr_path));
DataHandler attr_handler = new DataHandler(attr_ds);
right.setDataHandler(attr_handler);
right.setFileName(string.substring(string.lastIndexOf("/")));
mixed.addBodyPart(right);
}
}
/*************** 设置邮件内容: 多功能用户邮件 (related) *******************/
// 4.1 构建一个多功能邮件块
MimeMultipart related = new MimeMultipart("related");
// ----> 设置到总邮件快的左侧中
left.setContent(related);
// 4.2 构建多功能邮件块内容 = 左侧文本 + 右侧图片资源
MimeBodyPart content = new MimeBodyPart();
// MimeBodyPart resource = new MimeBodyPart();
// 设置具体内容: a.资源(图片)
// String filePath = Email.class.getResource("mm.png").getPath();
// DataSource ds = new FileDataSource(new File(filePath));
// DataHandler handler = new DataHandler(ds);
// resource.setDataHandler(handler);
// resource.setContentID("mm.png"); // 设置资源名称,给外键引用
// 设置具体内容: b.文本
// content.setContent("<img src='cid:mm.png'/> 第一次提交!", "text/html;charset=UTF-8");
content.setContent(textContent, "text/html;charset=UTF-8");
related.addBodyPart(content);
// related.addBodyPart(resource);
// 5. 发送
Transport trans = session.getTransport();
trans.connect(userEmail, password);
trans.sendMessage(message, message.getAllRecipients());
trans.close();
}
}
注意:
本地测试成功,项目发布到阿里云服务器出现问题:
由于服务器禁用25端口,需要申请开通25端口。
改用465端口进行stmp邮件发送服务。