java - Spring 如何发送带附件的邮件

标签 java

当尝试使用 zip mime 类型发送邮件时,会收到一些随机格式的附件。所以尝试通过硬编码改变mime类型,需要知道如何从bytearraysource对象获取mime类型

package com.mail.send;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MailImpl {
public static void main(String args[]) throws IOException{

    ApplicationContext context=new ClassPathXmlApplicationContext("Spring.xml");
    JavaMail javaMail=(JavaMail) context.getBean("JavaMail");
    System.out.println("after bean creation");
    String to="abc@gmail.com";
    String cc="xyz@gmail.com";
    String subject="Pdf notification";
    String content="PDF has been generated";
    boolean flag = true ;
    File file =new File("E:\\Sample.pdf");

    //byte [] sample=null;

    /*start of modify*/
     FileInputStream fin = null;
     byte fileContent[] = new byte[(int)file.length()];
    try {
        // create FileInputStream object
        fin = new FileInputStream(file);



        // Reads up to certain bytes of data from this input stream into an array of bytes.
        fin.read(fileContent);
        //create string from byte array
        String s = new String(fileContent);
        System.out.println("File content: " + s);
    }
    catch (FileNotFoundException e) {
        System.out.println("File not found" + e);
    }
    catch (IOException ioe) {
        System.out.println("Exception while reading file " + ioe);
    }
    finally {
        // close the streams using close method
        try {
            if (fin != null) {
                fin.close();
            }
        }
        catch (IOException ioe) {
            System.out.println("Error while closing stream: " + ioe);
        }
    }
    byte[] fileContent1 = null;

    /*end of modify */
    if(flag==true){
        fileContent1=zipBytes("Sample.pdf", fileContent);//document.getmimetype
    }else{
        fileContent1 = fileContent;
    }
    javaMail.sendEmail(to, cc, subject, content, fileContent1);


}

public static byte[] zipBytes(String filename, byte[] input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry(filename);
    entry.setSize(input.length);
    zos.putNextEntry(entry);
    zos.write(input);
    zos.closeEntry();
    zos.close();



    return baos.toByteArray();
}


}

最佳答案

包com.mail.send;

import java.io.File;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

//mailimpl 公共(public)类 JavaMail {

@Autowired
JavaMailSender mailSender;

public JavaMailSender getMailSender() {
    return mailSender;
}

public void setMailSender(JavaMailSender mailSender) {
    this.mailSender = mailSender;
}

String from = "pqr@gmail.com";

public void sendEmail(String to, String cc, String subject, String content,
        byte [] attachement) {
    try {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
        mimeMessageHelper.setFrom(from);
        mimeMessageHelper.setTo(to);
        mimeMessageHelper.setCc(cc);
        mimeMessageHelper.setSubject(subject);
        mimeMessageHelper.setText(content, true);
    //  mimeMessageHelper.addAttachment(attachement.getName(), attachement);

        //ByteArrayDataSource byteArrayDataSource=new ByteArrayDataSource(attachement, "application/zip");
        ByteArrayDataSource byteArrayDataSource = null;
        if(attachement.length > 10){
             byteArrayDataSource=new ByteArrayDataSource(attachement, "application/zip");
             mimeMessageHelper.addAttachment(byteArrayDataSource.getName(), byteArrayDataSource);

            }else{
                 byteArrayDataSource=new ByteArrayDataSource(attachement, "application/pdf");
                 mimeMessageHelper.addAttachment(byteArrayDataSource.getName()+".pdf", byteArrayDataSource);

            }
        //mimeMessageHelper.addAttachment(byteArrayDataSource.getName(), byteArrayDataSource);

        System.out.println("Start of mail");
        mailSender.send(mimeMessage);
        System.out.println("End of mail");

    } catch (Exception e) {
        System.out.println(e);
    }
}

}


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.mail.send" />

<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="localhost" />
    <property name="port" value="25" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.transport.protocol">smtp</prop>
            <prop key="mail.smtp.auth">false</prop>
            <prop key="mail.smtp.starttls.enable">true</prop>
        </props>
    </property>
</bean>

<bean id="JavaMail" class="com.mail.send.JavaMail">
    <property name="mailSender" ref="mailSender" />
</bean>

<!--    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    max upload size in bytes
    <property name="maxUploadSize" value="20971520" /> 20MB

    max size of file in memory (in bytes)
    <property name="maxInMemorySize" value="1048576" /> 1MB

</bean> -->
</beans>

关于java - Spring 如何发送带附件的邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39286295/

相关文章:

java - 如何停止 Gradle 将依赖项扩展为 ExpandedArchives?

java - 录音期间发生异常……!

java - 在 j2me 中使用什么 api 制作游戏应用程序

Java com口读写问题

java - 在 Java 的抽象类中使用 protected 字段

java - hibernate join fetch和二级缓存

java - Mongotemplate聚合-获取结果数

java - 安全地迭代一个被多线程访问的 ConcurrentHashMap

java - 为什么 Java Stack.push 会给出一个返回类型,即使我不需要它?

java - playframework2.0中的自定义标签或在模板中执行 equals