EmailSender.SendEmail()
方法发送邮件, 需要配置发送邮件的服务器配置
方法参数:
subject : 邮件主题
content: 邮件正文
to : 邮件接收人
cc : 邮件抄送人
attachments: 邮件附件
注意:
正文可以添加, html格式, 但邮件正文配置时, 必须有Html格式.
正文换行必须是<br>, 而不能是 换行字符
链接也是Html格式. <a></a>标签
String content = "Dear,<br>" +
"This is test message. <br>" +
"链接: <a href=XXXXXX>Test</a>";
package com.company; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.*; import java.io.File; import java.io.UnsupportedEncodingException; import java.util.Properties; public class EmailSender { public static void SendEmail(String subject, String content, String to, String cc, File attachments){ // 获取系统属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", "XXX"); // 指定发送邮件的主机 properties.setProperty("mail.smtp.post", "25"); properties.put("mail.smtp.auth", "true"); //允许授权用户 // 获取默认session对象 Session session = Session.getDefaultInstance(properties,new Authenticator(){ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("XXX", "*******"); //发件人邮件用户名、授权码 } }); // session.setDebug(true); //开启后有调试信息 try{ MimeMessage message = new MimeMessage(session); // 创建默认的 MimeMessage 对象。 // Set From: 头部头字段, // 发件人电子邮箱 message.setFrom(new InternetAddress("XXX")); // Set To: 发送人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set To: 抄送人 message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc)); // Set Subject: 邮件主题 message.setSubject(subject); // 添加附件 // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件 Multipart multipart = new MimeMultipart(); // 添加邮件正文 BodyPart contentPart = new MimeBodyPart(); contentPart.setContent(content, "text/html;charset=UTF-8"); multipart.addBodyPart(contentPart); // 添加附件的内容 if (attachments != null && attachments.length > 0) { BodyPart attachmentBodyPart = null; try { attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachments); attachmentBodyPart.setDataHandler(new DataHandler(source)); //MimeUtility.encodeWord可以避免文件名乱码 attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachments.getName())); multipart.addBodyPart(attachmentBodyPart); } catch (UnsupportedEncodingException e){ e.printStackTrace(); } } // 将multipart对象放到message中 message.setContent(multipart); // 发送消息 Transport.send(message); System.out.println("Sent message successfully..."); } catch (MessagingException mex) { mex.printStackTrace(); } } }