IT评测·应用市场-qidao123.com

标题: 用 Java 发送 HTML 内容并带附件的电子邮件 [打印本页]

作者: 曂沅仴駦    时间: 2025-1-24 02:16
标题: 用 Java 发送 HTML 内容并带附件的电子邮件
实现思路


以下是完整的 Java 代码示例:
  1. import javax.mail.*;
  2. import javax.mail.internet.*;
  3. import java.io.File;
  4. import java.util.Properties;
  5. public class HtmlAndAttachmentEmailSender {
  6.     public static void main(String[] args) {
  7.         // 邮件服务器的属性设置
  8.         Properties properties = new Properties();
  9.         properties.put("mail.smtp.auth", "true");
  10.         properties.put("mail.smtp.starttls.enable", "true");
  11.         properties.put("mail.smtp.host", "smtp.example.com");
  12.         properties.put("mail.smtp.port", "587");
  13.         // 发件人的邮箱账号和密码
  14.         String senderEmail = "your_email@example.com";
  15.         String senderPassword = "your_password";
  16.         // 创建会话对象
  17.         Session session = Session.getInstance(properties, new Authenticator() {
  18.             @Override
  19.             protected PasswordAuthentication getPasswordAuthentication() {
  20.                 return new PasswordAuthentication(senderEmail, senderPassword);
  21.             }
  22.         });
  23.         try {
  24.             // 创建邮件消息对象
  25.             MimeMessage message = new MimeMessage(session);
  26.             message.setFrom(new InternetAddress(senderEmail));
  27.             message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient_email@example.com"));
  28.             message.setSubject("HTML 内容并带附件的邮件");
  29.             // 创建一个多部分的邮件内容对象
  30.             Multipart multipart = new MimeMultipart();
  31.             // 第一部分:HTML 内容
  32.             BodyPart htmlPart = new MimeBodyPart();
  33.             String htmlContent = "<html><body><h1>嘿,这是一封带有附件的 HTML 邮件哦!</h1><p>是不是很赞呢?</p></body></html>";
  34.             htmlPart.setContent(htmlContent, "text/html; charset=utf-8");
  35.             multipart.addBodyPart(htmlPart);
  36.             // 第二部分:附件
  37.             BodyPart attachmentPart = new MimeBodyPart();
  38.             File file = new File("path/to/your/attachment.pdf"); // 这里替换为你要添加的附件的实际路径
  39.             attachmentPart.attachFile(file);
  40.             multipart.addBodyPart(attachmentPart);
  41.             // 将多部分内容设置到邮件消息中
  42.             message.setContent(multipart);
  43.             // 发送邮件
  44.             Transport.send(message);
  45.             System.out.println("HTML 内容并带附件的邮件发送成功!");
  46.         } catch (MessagingException | java.io.IOException e) {
  47.             e.printStackTrace();
  48.             System.out.println("邮件发送失败!");
  49.         }
  50.     }
  51. }
复制代码
代码表明



怎么样,小伙伴们,是不是很简朴呢 赶紧把这段代码用到你的项目中,让你的邮件更加丰富和强盛吧 不外,在使用过程中,记得处置处罚好异常环境,防止出现不测哦 有啥题目随时来问我,我会帮你解决的!


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com (https://dis.qidao123.com/) Powered by Discuz! X3.4