java mail imap 附件下载_Java Mail 发送带有附件的邮件

public classsendMail {/*** 创建邮件信息

*@paramsession

*@paramfromAccount

*@paramtoAccount

*@paramsourcePath xml文件目录 e.g. xml

*@paramzipPath zip文件目录 e.g. zip/person.zip*/

public static void CreateMessage(final Session session, final String fromAccount, final String toAccount,final String sourcePath,finalString zipPath){try{final String subjectStr="圣诞节快乐";//主题

final StringBuffer contentStr=new StringBuffer();//内容

contentStr.append("

Dear Friends,


");

contentStr.append("Christmas is coming up soon.
Wish you lots of love, joy &happiness. happy christmas.");

contentStr.append("

Regards,

").append("

ZHBIT College

");//创建默认的 MimeMessage 对象

final MimeMessage message = newMimeMessage(session);//Set From: 头部头字段

message.setFrom(newInternetAddress(fromAccount));//Set To: 头部头字段

message.addRecipient(Message.RecipientType.TO,newInternetAddress(toAccount));//Set Subject: 头部头字段

message.setSubject(subjectStr);//创建消息部分

final BodyPart messageBodyPart = newMimeBodyPart();//消息

messageBodyPart.setContent(contentStr.toString(),"text/html;charset=UTF-8");//创建多重消息

final Multipart multipart = newMimeMultipart();//设置文本消息部分

multipart.addBodyPart(messageBodyPart);//为邮件添加多个附件

MimeBodyPart attachment = null;final File source = newFile(sourcePath);if (!source.exists()) {

System.out.println(sourcePath+ " not exists");return;

}final File[] files =source.listFiles();for (finalFile f : files) {

attachment= newMimeBodyPart();final String filePath =f.getPath();//根据附件文件创建文件数据源

final DataSource ds = newFileDataSource(filePath);

attachment.setDataHandler(newDataHandler(ds));//为附件设置文件名

attachment.setFileName(ds.getName());

multipart.addBodyPart(attachment);

}//添加zip附件

attachment = newMimeBodyPart();//根据附件文件创建文件数据源

final DataSource ds = newFileDataSource(zipPath);

attachment.setDataHandler(newDataHandler(ds));//为附件设置文件名

attachment.setFileName(ds.getName());

multipart.addBodyPart(attachment);//发送完整消息

message.setContent(multipart);//发送消息

Transport.send(message);

}catch (finalMessagingException mex) {

mex.printStackTrace();

}

}/*** 将源文件目录下的所有文件打包成zip文件

*@paramsourceFilePath e.g. xml

*@paramzipFilePath e.g. zip

*@paramfileName e.g. person

*@return返回生成的zip文件目录 e.g. zip/person.zip*/

public static String tozip(final String sourceFilePath, finalString zipFilePath,finalString fileName) {final File sourceFile = newFile(sourceFilePath);

FileInputStream fis= null;

BufferedInputStream bis= null;

FileOutputStream fos= null;

ZipOutputStream zos= null;final String createZipPath=zipFilePath+ "/" + fileName+ ".zip";if(!sourceFile.exists()){

System.out.println("待压缩的文件目录:" + sourceFilePath + "不存在");

}else{try{final File zipFile = newFile(createZipPath);final File[] sourceFiles =sourceFile.listFiles();if(null == sourceFiles || sourceFiles.length < 1) {

System.out.println("待压缩的文件目录:" + sourceFilePath + " 里面不存在文件,无需压缩");

}else{

fos= newFileOutputStream(zipFile);

zos= new ZipOutputStream(newBufferedOutputStream(fos));final byte[] bufs = new byte[1024*10];for(int i=0;i

final ZipEntry zipEntry = newZipEntry(sourceFiles[i].getName());

zos.putNextEntry(zipEntry);//读取待压缩的文件并写进压缩包里

fis = newFileInputStream(sourceFiles[i]);

bis= new BufferedInputStream(fis,1024*10);int read = 0;while((read=bis.read(bufs, 0, 1024*10)) != -1) {

zos.write(bufs,0, read);

}

}

}

}catch (finalFileNotFoundException e) {

e.printStackTrace();throw newRuntimeException(e);

}catch (finalIOException e) {

e.printStackTrace();throw newRuntimeException(e);

}finally{try{if (null !=bis) {

bis.close();

}if (null !=zos) {

zos.close();

}

}catch (finalIOException e) {

e.printStackTrace();throw newRuntimeException(e);

}

}

}returncreateZipPath;

}public static void main(finalString[] args) {//收件人电子邮箱

final String toAccount = "********@qq.com";//发件人的 邮箱 和 密码

final String fromAccount = "**********@163.com";final String fromPassword = "**********";//指定发送邮件的主机

final String host = "smtp.163.com";//创建参数配置, 获取系统属性

final Properties properties =System.getProperties();

properties.setProperty("mail.transport.protocol", "smtp");

properties.setProperty("mail.smtp.host", host);

properties.put("mail.smtp.auth", "true");//根据配置创建会话对象,获取默认session对象

final Session session = Session.getDefaultInstance(properties,newAuthenticator(){

@OverridepublicPasswordAuthentication getPasswordAuthentication()

{return new PasswordAuthentication(fromAccount, fromPassword); //发件人邮件用户名、密码

}

});

session.setDebug(true);final String xmlPath="xml";final String zipPath=tozip(xmlPath,"zip","person");

CreateMessage(session,fromAccount,toAccount,xmlPath,zipPath);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来回答你的问题。 要使用Java读取邮件附件,可以按照以下步骤进行: 1. 导入JavaMail API和Java Activation Framework库。 2. 创建一个IMAP会话对象,连接到邮件服务器。 ```java Properties props = new Properties(); props.setProperty("mail.store.protocol", "imap"); Session session = Session.getInstance(props, null); Store store = session.getStore(); store.connect("mail.server.com", "username", "password"); ``` 3. 打开INBOX文件夹,获取所有的邮件。 ```java Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); Message[] messages = inbox.getMessages(); ``` 4. 遍历所有邮件,获取邮件附件。 ```java for (Message message : messages) { String subject = message.getSubject(); String from = message.getFrom()[0].toString(); String text = getTextFromMessage(message); System.out.println("Subject: " + subject); System.out.println("From: " + from); System.out.println("Text: " + text); // 获取邮件附件 Multipart multipart = (Multipart) message.getContent(); for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); if (bodyPart.getDisposition() != null && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) { String fileName = bodyPart.getFileName(); InputStream is = bodyPart.getInputStream(); // 处理附件内容 // ... } } } ``` 5. 处理附件内容的方法。 ```java private void processAttachment(InputStream is, String fileName) throws IOException { FileOutputStream fos = new FileOutputStream(fileName); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = is.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } fos.close(); is.close(); } ``` 以上就是使用Java读取邮件附件的基本步骤。需要注意的是,邮件服务器的配置信息需要根据实际情况进行修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值