Java邮件发送
package com.expai.test;
import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; 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; public class SendMail { public static void main(String[] args) { senMail("d:/测试.xls","163","[email protected]","hjr15135149189","[email protected]","Excel文档","Hi,记得查收邮件哦!"); } //category用哪种邮箱发送 //fromMailAddress发件邮箱地址 //fromMailPassword发件邮箱密码 //toMailAddress收件邮箱地址 //mailTitle邮件标题 //mailContent邮件文本内容 public static void senMail(String fileName,String category,String fromMailAddress,String fromMailPassword,String toMailAddress,String mailTitle,String mailContent){ Properties props = System.getProperties(); // 设置smtp服务器 props.setProperty("mail.smtp.host", "smtp."+category+".com"); // 现在的大部分smpt都需要验证了 props.put("mail.smtp.auth", "true"); Session s = Session.getInstance(props); // 为了查看运行时的信息 s.setDebug(true); // 由邮件会话新建一个消息对象 MimeMessage message = new MimeMessage(s); try { // 发件人 InternetAddress from = new InternetAddress(fromMailAddress); message.setFrom(from); // 收件人 InternetAddress to = new InternetAddress(toMailAddress); message.setRecipient(Message.RecipientType.TO, to); // 邮件标题 message.setSubject(mailTitle); String content = mailTitle; // 邮件内容,也可以使纯文本"text/plain" message.setContent(content, "text/html;charset=GBK"); /****下面代码是发送附件*******/ MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(mailContent); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileName); messageBodyPart.setDataHandler(new DataHandler(source)); //去掉文件路径得到文件名 fileName = fileName.substring(fileName.indexOf("/")+1,fileName.length()); //解决文件中文名乱码问题GBk经测试不行 sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); messageBodyPart.setFileName("=?UTF-8?B?"+enc.encode(fileName.getBytes())+"?="); //messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); message.setContent(multipart); message.saveChanges(); Transport transport = s.getTransport("smtp"); // smtp验证,就是你用来发邮件的邮箱用户名密码 transport.connect("smtp."+category+".com", fromMailAddress, fromMailPassword); // 发送 transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Exception e) { e.printStackTrace(); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。