首页 > 代码库 > Java邮件发送
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","houjinrong767@163.com","hjr15135149189","houjinrong@expai.com","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(); } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。