java实现发送邮件功能
作者:互联网
java实现发送邮件功能
- <!--发送邮件-->
- <dependency>
- <groupId>javax.mail</groupId>
- <artifactId>mail</artifactId>
- <version>1.4.7</version>
- </dependency>
-
- import org.apache.tomcat.util.descriptor.web.WebXml;
-
- import java.util.Date;
- import java.util.Properties;
- import javax.mail.Message.RecipientType;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
-
- public class MailUtils {
- //服务器的地址
- public static final String SMTPSERVER = "xxx";
- //服务器的端口
- public static final String SMTPPORT = "xxx";
- //服务器的账号
- public static final String ACCOUT = "xxxxx";
- //服务器的密码
- public static final String PWD = "xxxxxx";
- //发件人的账号
- public static final String emailform = "xxxxx";
-
- public static void main(String[] args) throws Exception {
- String emailto = "xxxxxxxxxx";
- String subject = "(出差人英文名)取消出差通知";
- String content= "<出差人英文名>原计划(时间含yyyy/mm/dd hh:mm)xx到xx,从(地点)xx到xx进行出差。先提出取消,请知晓!\n" +
- "【取消原因】\n" +
- "Xxxxx\n" +
- "【原出差目的】\n" +
- "Xxxxx\n";
- MailUtils.sendEmail( emailto, subject, content);
- }
-
- public static void sendEmail(String emailto,String subject,String content) {
- try {
- // 创建邮件配置
- Properties props = new Properties();
- props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
- props.setProperty("mail.smtp.host", SMTPSERVER); // 发件人的邮箱的 SMTP 服务器地址
- props.setProperty("mail.smtp.port", SMTPPORT);
- props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- // props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
- // props.setProperty("mail.smtp.ssl.enable", "true");// 开启ssl
-
-
- // 根据邮件配置创建会话,注意session别导错包
- Session session = Session.getDefaultInstance(props);
- // 开启debug模式,可以看到更多详细的输入日志
- session.setDebug(true);
- //创建邮件
- MimeMessage message = createEmail(session, emailto, subject, content);
- //获取传输通道
- Transport transport = session.getTransport();
- transport.connect(SMTPSERVER,ACCOUT, PWD);
- //连接,并发送邮件
- transport.sendMessage(message, message.getAllRecipients());
- transport.close();
- }catch (Exception e){
- e.printStackTrace();
- }
-
-
-
- }
-
-
- private static MimeMessage createEmail(Session session, String emailto,String subject,String content) throws Exception {
- // 根据会话创建邮件
- MimeMessage msg = new MimeMessage(session);
- // address邮件地址, personal邮件昵称, charset编码方式
- InternetAddress fromAddress = new InternetAddress(emailform,
- "", "utf-8");
- // 设置发送邮件方
- msg.setFrom(fromAddress);
-
- InternetAddress receiveAddress = new InternetAddress(
- emailto, "", "utf-8");
- // 设置邮件接收方
- msg.setRecipient(RecipientType.TO, receiveAddress);
- // 设置邮件标题
- msg.setSubject(subject, "utf-8");
- msg.setText(content);
- // 设置显示的发件时间
- msg.setSentDate(new Date());
- // 保存设置
- msg.saveChanges();
- return msg;
- }
- }
https://blog.csdn.net/liu154794/article/details/98964549
标签:java,String,import,发送,static,props,mail,邮件 来源: https://www.cnblogs.com/sunny3158/p/16656342.html