Java邮件发送方法
引入依赖
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>
邮件发送代码:
package com.huiju.les.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* @author chenCaiDao
* @projectName WMSProject
* @title: SendMail
* @description:
* @date 2023/10/27 10:43
*/
public class SendMail {
private static final Logger log = LoggerFactory.getLogger(SendMail.class);
public static void main(String[] args) throws Exception {
sendPlainEmail("这是一个subject", "this is content");
}
public static void sendPlainEmail(String subject, String content) {
String from = "gongshi@unicorecomm.com";
String host = "45.*.*.75";
String password = "******";
String username = "gongshi@unicorecomm.com";
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", host);
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "SMTP");
Session session = Session.getInstance(props);
session.setDebug(true);
try {
String operator_email = "chencaidao@unicorecomm.com";
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(operator_email));
message.setSubject(subject);
//message.setText("Welcome to JavaMail World!");
message.setContent(content,"text/html;charset=utf-8");
Transport transport=session.getTransport("smtp");
transport.connect(host,25, username, password);
log.info("====发送邮件前operator_email==="+operator_email);
transport.sendMessage(message,message.getAllRecipients());
log.info("====发送邮件给operator_email==="+operator_email);
transport.close();
log.info("====done===");
} catch (Exception e) {
e.printStackTrace();
}
}
}
邮件发送效果: