java实现发送邮件功能(可以添加附件)

记录一下在java中发送邮件的实现方式,下面这个工具类是根据在网上查阅的资料自己整理出来的。

类中只有两个方法:
1.第一个就是普通的发送文本内容邮件的方法。
2.第二个是能发送附件邮件的方法。如果还想实现更复杂的可以自行百度。

一、pom依赖

1.maven项目

<dependencies>
    <!-- JavaMail API -->
    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.6.2</version>
    </dependency>
    
    <!-- JavaBeans Activation Framework (JAF) -->
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
</dependencies>

上述依赖项包含了JavaMail API和JavaBeans Activation Framework(JAF)。JavaMail API用于发送和接收电子邮件,而JAF用于处理邮件附件的类型和编码。

2.SpringBoot项目

<dependencies>
    <!-- Spring Boot Mail Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-mail</artifactId>
    </dependency>
</dependencies>

要在Spring Boot项目中发送电子邮件,你可以使用Spring Boot提供的spring-boot-starter-mail依赖项。该依赖项集成了JavaMail API,并提供了更方便的配置和使用方式。
上述依赖项将自动引入Spring Boot Mail Starter,并解决其所需的传递依赖关系。它包含了JavaMail API以及Spring Boot中发送电子邮件所需的其他组件。

二、代码

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;
public class MailUtil{
    
    // 发件人邮箱的邮件服务器地址(SMTP)
    // 必须准确,不同邮件服务器地址不同,QQ邮箱的 SMTP 服务器地址为: smtp.qq.com
    public static String myEmailSMTPHost = "smtp.qq.com";

    /**
     * 发送纯文本邮件
     * 
     * @param mailTitle 邮件主题
     * @param content 邮件内容
     * @param sendMail 发件人邮箱地址
     * @param sendName 发件人姓名
     * @param receiveMail 收件人
     * @param sendMailPassword 发送人邮箱密码
     *            某些邮箱服务器为了增加邮箱本身密码的安全性,给SMTP客户端设置了独立密码(有的邮箱称为“授权码”),
     *            对于开启了独立密码的邮箱,这里的邮箱密码必需使用这个独立密码(授权码)。
     * 
     * @return
     * @throws Exception
     */
     public static void sendEmail(String mailTitle, String content, String sendMail, String sendName,
                   String receiveMail, String sendMailPassword) throws Exception{
         Properties p = new Properties();
         p.setProperty("mail.transport.protocol", "smtp");// 使用的协议
         p.setProperty("mail.smtp.host", myEmailSMTPHost);
         p.setProperty("mail.smtp.localhost", "localhost");// 不加的话在linux报错:501 syntax:ehlo hostname
         p.setProperty("mail.smtp.auth", "true");// 需要请求认证
         
         Session session = Session.getInstance(p);
         //设置为debug模式,可以查看详细的发送log
         session.setDebug(true);
         
         MimeMessage message = new MimeMessage(session);
         //发件人
         message.setFrom(new InternetAddress(sendMail, sendName, "UTF-8"));

         //收件人
         message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, receiveMail, "UTF-8"));

         //邮件主题
         message.setSubject(mailTitle, "UTF-8");

         //邮件正文
         message.setContent(content, "text/html;charset=UTF-8");

         //设置显示的发件时间
         message.setSentDate(new Date());

         //保存前面的设置
         message.saveChanges();

         //根据session获取邮件传输对象
         Transport transport = session.getTransport();
         //连接邮箱服务器
         transport.connect(sendMail, sendMailPassword);
         //发送邮件到所有的收件地址
         transport.sendMessage(message, message.getAllRecipients());
         transport.close();
     }

      //和上边方法基本相同,只不过可以添加附件发送邮件
      public static void sendEmailWithFile(String mailTitle, String content, String sendMail, String sendName,
                   List<String> receiveMailList, String sendMailPassword) throws Exception{
         Properties p = new Properties();
         p.setProperty("mail.transport.protocol", "smtp");
         p.setProperty("mail.smtp.host", myEmailSMTPHost);
         //p.setProperty("mail.smtp.localhost", "localhost");//不加的话在linux报错:501 syntax:ehlo hostname
         p.setProperty("mail.smtp.auth", "true");
   
         Session session = Session.getInstance(p);
         //设置为debug模式,可以查看详细的发送log
         session.setDebug(true);
         
         MimeMessage message = new MimeMessage(session);
         //发件人
         message.setFrom(new InternetAddress(sendMail, sendName, "UTF-8"));

         //收件人
         for(String receiveAddress : receiveMailList){
             message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveAddress, receiveAddress, "UTF-8"));
         }

         //邮件主题
         message.setSubject(mailTitle, "UTF-8");

         //向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
         MimeMultipart multipart = new MimeMultipart();
         //设置邮件的文本内容
         MimeBodyPart contentPart = new MimeBodyPart();
         contentPart.setContent(content, "text/html;charset=UTF-8");
         multipart.addBodyPart(contentPart);
         //添加附件
         MimeBodyPart filePart = new MimeBodyPart();
         DataSource source = new FileDataSource("E:\\file_path" + File.separator + "附件.xlsx");
         //添加附件的内容
         filePart.setDataHandler(new DataHandler(source));
         //添加附件的标题
         filePart.setFileName(MimeUtility.encodeText("附件.xlsx"));
         multipart.addBodyPart(filePart);
         multipart.setSubType("mixed");
         //将multipart对象放到message中
         message.setContent(multipart);

         //设置显示的发件时间
         message.setSentDate(new Date());

         //保存前面的设置
         message.saveChanges();

         //根据session获取邮件传输对象
         Transport transport = session.getTransport();
         //连接邮箱服务器
         transport.connect(sendMail, sendMailPassword);
         //发送邮件到所有的收件地址
         transport.sendMessage(message, message.getAllRecipients());
         transport.close();
     }
}

另外,邮件的内容(content)也可以通过拼接html代码来发送文本内容格式是表格的邮件,如下:

content = "<html><head><head><body><table>" +
          "<tr>" + 
          "<td>第一个单元格</td>" +
          "<td>第二个单元格</td>" +
          "</tr>" + 
          "</table></body></html>"

按上边这个content发送的邮件内容将展示为一个表格。

好了,有不同意见的欢迎留言哈~

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
利用Java发送邮件(含附件)的例子 1、邮件发送的配置propertity文件内容如下:(utils.properties文件放在src下面) [email protected]=******2、读取配置文件的类文件(ReadPropertity.java) import java.io.IOException;import java.util.Properties;public class ReadPropertity { static Properties props = new Properties(); static { try { props.load(ReadPropertity.class.getClassLoader().getResourceAsStream( "utils.properties")); } catch (IOException e1) { e1.printStackTrace(); } } public static String getProperty(String key) { return props.getProperty(key); }}3、邮件处理类(EmailHandle.java)import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.BodyPart;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;import javax.mail.internet.MimeUtility;/*** 本程序用java实现Email的发送, 所用到的协议为:smtp* <p>Company: 疯狂的IT人</p>* time:2013-04-05* @author www.crazyiter.com* @date * @version 1.0 */public class EmailHandle { private MimeMessage mimeMsg; //邮件对象 private Session session; //发送邮件的Session会话 private Properties props;//邮件发送时的一些配置信息的一个属性对象 private String sendUserName; //发件人的用户名 private String sendUserPass; //发件人密码 private Multipart mp;//附件添加的组件 private List files = new LinkedList();//存放附件文件 public EmailHandle(String smtp) { sendUserName = ""; sendUserPass = ""; setSmtpHost(smtp);// 设置邮件服务器 createMimeMessage(); // 创建邮件 } public void setSmtpHost(String hostName) { if (props == null) props = System.getProperties(); props.put("mail.smtp.host", hostName); } public boolean createMimeMessage(){ try { // 用props对象来创建并初始化session对象 session = Session.getDefaultInstance(props, null); } catch (Exception e) { System.err.println("获取邮件会话对象时发生错误!" + e); return false; } try { mimeMsg = new MimeMessage(session); // 用session对象来创建并初始化邮件对象 mp = new MimeMultipart();// 生成附件组件的实例 } catch (Exception e) { return false; } return true; } /** * 设置SMTP的身份认证 */ public void setNeedAuth(boolean need) { if (props == null) props = System.getProperties(); if (need) props.put("mail.smtp.auth", "true"); else props.put("mail.smtp.auth", "false"); } /** * 进行用户身份验证时,设置用户名和密码 */ public void setNamePass(String name, String pass) { sendUserName = name; sendUserPass = pass; } /** * 设置邮件主题 * @param mailSubject * @return */ public boolean setSubject(String mailSubject) { try { mimeMsg.setSubject(mailSubject); } catch (Exception e) { return false; } return true; } /** * 设置邮件内容,并设置其为文本格式或HTML文件格式,编码方式为UTF-8 * @param mailBody * @return */ public boolean setBody(String mailBody) { try { BodyPart bp = new MimeBodyPart(); bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=UTF-8>"+ mailBody, "text/html;charset=UTF-8"); // 在组件上添加邮件文本 mp.addBodyPart(bp); } catch (Exception e) { System.err.println("设置邮件正文时发生错误!" + e); return false; } return true; } /** * 增加发送附件 * @param filename * 邮件附件的地址,只能是本机地址而不能是网络地址,否则抛出异常 * @return */ public boolean addFileAffix(String filename) { try { BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(MimeUtility.encodeText(fileds.getName(),"utf-8",null)); // 解决附件名称乱码 mp.addBodyPart(bp);// 添加附件 files.add(fileds); } catch (Exception e) { System.err.println("增加邮件附件:" + filename + "发生错误!" + e); return false; } return true; } public boolean delFileAffix(){ try { FileDataSource fileds = null; for(Iterator it = files.iterator() ;it.hasNext();) { fileds = (FileDataSource)it.next(); if(fileds != null && fileds.getFile() != null){ fileds.getFile().delete(); } } }catch (Exception e) { return false; } return true; } /** * 设置发件人地址 * @param from * 发件人地址 * @return */ public boolean setFrom(String from) { try { mimeMsg.setFrom(new InternetAddress(from)); } catch (Exception e) { return false; } return true; } /** * 设置收件人地址 * @param to收件人的地址 * @return */ public boolean setTo(String to) { if (to == null) return false; try { mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to)); } catch (Exception e) { return false; } return true; } /** * 发送附件 * @param copyto * @return */ public boolean setCopyTo(String copyto) { if (copyto == null) return false; try { mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC,InternetAddress.parse(copyto)); } catch (Exception e) { return false; } return true; } /** * 发送邮件 * @return */ public boolean sendEmail() throws Exception{ mimeMsg.setContent(mp); mimeMsg.saveChanges(); System.out.println("正在发送邮件...."); Session mailSession = Session.getInstance(props, null); Transport transport = mailSession.getTransport("smtp"); // 连接邮件服务器并进行身份验证 transport.connect((String) props.get("mail.smtp.host"), sendUserName,sendUserPass); // 发送邮件 transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO)); System.out.println("发送邮件成功!"); transport.close(); return true; }}4、邮件发送的类文件(SendEmail.java)/*** 发送邮件测试* <p>Company: 疯狂的IT人</p>* time:2013-04-05* @author www.crazyiter.com* @date * @version 1.0 */public class SendEmail { public SendEmail() { } /***以后需要两个参数:接收方地址 、 内容***/ public static void send(String subject, String toaddress,String content)throws Exception { String hostName = ReadPropertity.getProperty("emailsmtp"); String fromAddress = ReadPropertity.getProperty("emailaddress"); String fromAPass = ReadPropertity.getProperty("emailpass"); EmailHandle emailHandle = new EmailHandle(hostName); emailHandle.setFrom(fromAddress); emailHandle.setNeedAuth(true); emailHandle.setSubject(subject); emailHandle.setBody(content); emailHandle.setTo(toaddress); emailHandle.setFrom(fromAddress); emailHandle.addFileAffix("D:/myself/help/txt/java环境变量.txt");// 附件文件路径 emailHandle.setNamePass(fromAddress, fromAPass); emailHandle.sendEmail(); } public static void main(String[] args) { try { SendEmail.send("带附件的邮件测试","[email protected]","测试内容<a href='http://www.crazyiter.com'>疯狂的IT人</a>"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}5、发送邮件需要的jar包:activation.jarmail-plugin.jarmail.jar6、打包下载: 疯狂的IT人整理java邮件发送(源码).rar 下载地址: http://www.crazyiter.com/bbs/forum.php?mod=attachment&aid=MjF8MzQzOTYzZjB8MTM2NTE3NjczMHwxfDExNDA%3D
好的,以下是 Java 实现附件的邮件发送功能的步骤: 1. 导入 JavaMailJava Activation Framework 库。 2. 创建一个 Session 对象,设置邮箱服务器的相关信息,包括主机名、端口号、是否开启 SSL 等。这些信息可以从你的邮箱提供商那里获取。 3. 创建一个 MimeMessage 对象,设置邮件的基本信息,包括发件人、收件人、主题等。 4. 创建一个 MimeMultipart 对象,用于存放邮件正文和附件。 5. 创建一个 MimeBodyPart 对象,设置邮件正文的内容和格式。 6. 创建一个 MimeBodyPart 对象,设置附件的内容和格式。 7. 将邮件正文和附件添加到 MimeMultipart 对象中。 8. 将 MimeMultipart 对象设置为 MimeMessage 对象的内容。 9. 发送邮件。 以下是一个简单的示例代码: ```java import javax.mail.*; import javax.mail.internet.*; import java.util.Properties; public class SendEmailWithAttachment { public static void main(String[] args) throws Exception { // 邮箱服务器信息 String host = "smtp.example.com"; String username = "your_username"; String password = "your_password"; int port = 587; boolean ssl = false; // 收件人信息 String to = "[email protected]"; // 创建 Session 对象 Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", port); props.put("mail.smtp.starttls.enable", ssl ? "true" : "false"); Session session = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); // 创建邮件对象 MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("邮件主题"); // 创建邮件正文 MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("邮件正文"); // 创建附件 MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile("path/to/attachment"); // 创建混合内容 MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(textPart); multipart.addBodyPart(attachmentPart); // 设置邮件内容 message.setContent(multipart); // 发送邮件 Transport.send(message); } } ``` 其中,`host`、`username`、`password`、`port` 和 `ssl` 为你的邮箱服务器相关信息,`to` 为收件人邮箱地址,`path/to/attachment` 为附件的路径。你需要将这些信息替换为自己的信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值