java发送带附件的邮件

java发邮件有三种方式:

一、使用javax.mail传统方式。需引入mail-1.4.jar包。这是用java自带的类库实现,但是实现起来比较麻烦。

二、使用Apache Commons Mail方式。需要引入commons-email-1.2.jar包。用MultiPartEmail对象,设置完邮箱信息和EmailAttachment附件对象后,使用send方法发送。

		//附件,可以定义多个附件对象
		EmailAttachment attachment = new EmailAttachment();
		attachment.setPath("C:\\123.txt");
		attachment.setDisposition(EmailAttachment.ATTACHMENT);
		attachment.setDescription("这是附件描述");
		MultiPartEmail email = new MultiPartEmail();

		email.setHostName("smtp.163.com");  //设置发送主机的服务器地址
		email.addTo("xxx");   //设置收件人邮箱
		email.setFrom("xxx");   //发件人邮箱
		email.setAuthentication("用户名", "密码");//设置发件人在邮件服务器上注册的用户名和密码  
		email.setCharset("UTF-8");    //设置主题的字符集 
		email.setSubject("你好, 这是邮件主题");  //设置邮件的主题
		email.setMsg("这是邮件正文部分");  //邮件正文内容
		email.attach(attachment);     //添加附件			
		email.send();

 

三、使用spring框架方式。需引入spring-context-support-4.3.9.jar包。使用MimeMessageHelper对象发送。

        JavaMailSender javaMailSender = new JavaMailSenderImpl();
        
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "UTF-8");
        
        messageHelper.setTo(tos);//邮件接收人
        messageHelper.setFrom(text);//邮件内容 
        messageHelper.setSubject(subject);//主题
        messageHelper.setText(text, true);// true 表示启动HTML格式的邮件
        
        FileSystemResource file = new FileSystemResource(new File("c://123.txt"));
        messageHelper.addAttachment(AttachName, file);// 发送邮件
        javaMailSender.send(mailMessage);  

 

最后附上发邮件工具类:

配置类:

package cn.com.maxntech.email;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component("mailConfig")
@ConfigurationProperties(prefix = "application.email")
public class MailConfig {
    private String host;
    private String username;
    private String password;
    private String auth;
    //省略get set
}

工具类:

package cn.com.maxntech.hu.utils;

import java.io.File;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import cn.com.maxtech.email.MailConfig;

/**
 * 邮件发送工具类
 * */
@Component
public class SendMailUtils {
	
	@Autowired
	private MailConfig mailConfig;
	@Autowired
	private JavaMailSender javaMailSender;

    /**
     * 发送带html格式的邮件
     * @param tos
     * @param subject
     * @param text
     * @throws Exception
     */
	public void sendTextWithHtml(String[] tos, String subject, String text)  
            throws Exception {  
        MimeMessage mailMessage = javaMailSender.createMimeMessage();  
        initMimeMessageHelper(mailMessage, tos, mailConfig.getUsername(), subject, text);  
        // 发送邮件  
        javaMailSender.send(mailMessage);  
    }

    /**
     * 发送带图片的邮件
     * @param tos
     * @param subject
     * @param text
     * @param imgId
     * @param imgPath
     * @throws MessagingException
     */
    public void sendTextWithImg(String[] tos, String subject, String text,  
            String imgId, String imgPath) throws MessagingException {  
        MimeMessage mailMessage = javaMailSender.createMimeMessage();  
        MimeMessageHelper messageHelper = initMimeMessageHelper(mailMessage,tos,mailConfig.getUsername(),subject, text,true, true, "UTF-8");  
        // 发送图片  
        FileSystemResource img = new FileSystemResource(new File(imgPath));  
        messageHelper.addInline(imgId, img);  
        // 发送邮件  
        javaMailSender.send(mailMessage);  
    }

    /**
     * 发送带附件的邮件
     * @param tos
     * @param subject
     * @param text
     * @param AttachName
     * @param filePath
     * @throws MessagingException
     */
    public void sendWithAttament(String[] tos, String subject, String text,  
            String AttachName, String filePath) throws MessagingException {  
        MimeMessage mailMessage = javaMailSender.createMimeMessage();  
        MimeMessageHelper messageHelper = initMimeMessageHelper(mailMessage, tos, mailConfig.getUsername(), subject, text,  
                true, true, "UTF-8");  
        FileSystemResource file = new FileSystemResource(new File(filePath));  
        // 发送邮件  
        messageHelper.addAttachment(AttachName, file);  
        javaMailSender.send(mailMessage);  
    }

    /**
     * 发送带图片和附件的邮件
     * @param tos
     * @param from
     * @param subject
     * @param text
     * @param imgId
     * @param imgPath
     * @param AttachName
     * @param filePath
     * @throws MessagingException
     */
    public void sendWithAll(String[] tos, String from, String subject, String text,  
            String imgId, String imgPath, String AttachName, String filePath) throws MessagingException {  
        MimeMessage mailMessage = javaMailSender.createMimeMessage();  
        MimeMessageHelper messageHelper = initMimeMessageHelper(mailMessage, tos, mailConfig.getUsername(), subject, text,  
                true, true, "UTF-8");  
        // 插入图片  
        FileSystemResource img = new FileSystemResource(new File(imgPath));  
        messageHelper.addInline(imgId, img);  
        // 插入附件  
        FileSystemResource file = new FileSystemResource(new File(filePath));  
        messageHelper.addAttachment(AttachName, file);  
        // 发送邮件  
        javaMailSender.send(mailMessage);  
    }

    /**
     * 初始化helper
     * @param mailMessage
     * @param tos
     * @param from
     * @param subject
     * @param text
     * @return
     * @throws MessagingException
     */
    private  MimeMessageHelper initMimeMessageHelper(MimeMessage mailMessage, String[] tos, String from,  
            String subject, String text) throws MessagingException {  
        return initMimeMessageHelper(mailMessage, tos, from, subject, text, true, false, "UTF-8");  
    }

    /**
     * 初始化helper
     * @param mailMessage
     * @param tos
     * @param from
     * @param subject
     * @param text
     * @param isHTML
     * @param multipart
     * @param encoding
     * @return
     * @throws MessagingException
     */
    private static MimeMessageHelper initMimeMessageHelper(MimeMessage mailMessage, String[] tos, String from,  
            String subject, String text, boolean isHTML, boolean multipart, String encoding) throws MessagingException {  
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, multipart, encoding);  
        messageHelper.setTo(tos);  
        messageHelper.setFrom(from);  
        messageHelper.setSubject(subject);  
        // true 表示启动HTML格式的邮件  
        messageHelper.setText(text, isHTML);  
        return messageHelper;  
    }  
}  

 

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 JavaMail API 来发送附件邮件。下面是一个简单的示例代码: ```java import javax.mail.*; import javax.mail.internet.*; import java.util.*; public class SendMailWithAttachment { public static void main(String[] args) { // 发件人邮箱地址和密码 final String senderEmail = "[email protected]"; final String senderPassword = "your_email_password"; // 收件人邮箱地址 String recipientEmail = "[email protected]"; // 邮件主题和正文 String emailSubject = "Test email with attachment"; String emailBody = "This is a test email with attachment."; // 附件文件路径 String attachmentFilePath = "path/to/attachment/file"; // 发送邮件 Properties properties = new Properties(); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); Session session = Session.getInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(senderEmail, senderPassword); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(senderEmail)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail)); message.setSubject(emailSubject); // 创建邮件正文部分 MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(emailBody); // 创建附件部分 MimeBodyPart attachmentBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachmentFilePath); attachmentBodyPart.setDataHandler(new DataHandler(source)); attachmentBodyPart.setFileName(source.getName()); // 将正文部分和附件部分组合成混合的 MimeMultipart 对象 Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); multipart.addBodyPart(attachmentBodyPart); // 将混合的 MimeMultipart 对象设置为整个邮件的内容 message.setContent(multipart); // 发送邮件 Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { System.out.println("Failed to send email. Error message: " + e.getMessage()); } } } ``` 在代码中,需要将 `senderEmail` 和 `senderPassword` 替换为发件人的邮箱地址和密码,将 `recipientEmail` 替换为收件人的邮箱地址,将 `emailSubject` 和 `emailBody` 替换为邮件的主题和正文,将 `attachmentFilePath` 替换为附件文件的路径。 使用 JavaMail API 发送附件邮件需要注意以下几点: - 需要引入 JavaMail API 和 Java Activation Framework(JAF)的库。 - 需要设置邮件服务器的地址和端口号,例如 Gmail 的地址是 smtp.gmail.com,端口号是 587。 - 需要使用 `javax.mail.Authenticator` 类创建一个实现了 `getPasswordAuthentication()` 方法的子类来提供发件人邮箱地址和密码。 - 需要创建一个 `MimeMessage` 对象来表示邮件,设置发件人、收件人、主题和内容。 - 需要创建一个 `MimeBodyPart` 对象来表示附件,将附件文件的数据源和文件名设置到 `DataHandler` 和 `setFileName()` 方法中,然后将其添加到混合的 `MimeMultipart` 对象中。 - 需要将邮件的正文部分和附件部分组合成混合的 `MimeMultipart` 对象,然后将其设置为整个邮件的内容。 - 最后调用 `Transport.send()` 方法将邮件发送出去。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值