在java中发送带附件的邮件

时间:2015-04-02 12:56:31

标签: javamail

我想使用以下条件在java中发送带附件的邮件 -

  1. 我要附加的文件是可下载的URL (例如:http://berkeleycollege.edu/browser_check/samples/excel.xls

  2. 代码部署在appengine上,因此google禁止写入文件,创建文件,保存文件。

  3. 我甚至没有权限首先下载文件并将其作为附件附上。
  4. 我已经尝试InputStream input = new URL(url).openStream();来读取文件内容传递给数据处理程序。上面提到url的地方。示例代码:

    Message msg = new MimeMessage(session);
    Multipart multiPart = new MimeMultipart();
    MimeBodyPart attachment = new MimeBodyPart();
    DataHandler handler;
    InputStream input = new URL(url).openStream();
    handler = new DataHandler(new ByteArrayDataSource(input,"xls");
    attachment.setDataHandler(handler);
    multiPart.addBodyPart(attachment);
    msg.setContent(multiPart);
    Transport.send(msg);
    
  5. 上面的代码显示Invalid Content错误。

  6. 无论如何,我可以阅读该可下载链接的内容,并且该内容可以作为附件发送吗?

    请分享代码段以供参考。

1 个答案:

答案 0 :(得分:0)

Map model = new HashMap();
                String text = null;
                Properties properties_mail = new Properties();
                InputStream iStream_mail = null;
                String propFileName_mail = "properties/mail.properties";
                InputStream stream_mail =  getClass().getClassLoader().getResourceAsStream(propFileName_mail);
                properties_mail.load(stream_mail);

                    MimeMessage message = this.javamailsenderImpl.createMimeMessage();
                    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, MimeMessageHelper.MULTIPART_MODE_RELATED, "UTF-8");
                    mimeMessageHelper.setFrom(properties_mail.getProperty("javaMailSender.username"));
                    mimeMessageHelper.setTo(user.getUserEmail());
                    mimeMessageHelper.setSubject("Bpa Qa Product - New Organisation User");
                    /*String mailBody = "Welcome New User!!! <br /> Your Login Id is : "+user.getUserEmail()+"Your Password is:"+user.getUserPassword();
                    mimeMessageHelper.setText(mailBody, true);*/
                    model.put("firstName", user.getFirstName());
                    model.put("userEmail", user.getUserEmail());
                    model.put("userPassword", user.getUserPassword());
                    model.put("organizationName", user.getOrganization().getOrganizationName());
                    model.put("heading", "Thank You for Registering with us .!! Here is your Login credentials.");

                    text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "UserDetails.vm", "UTF-8", model);
                    mimeMessageHelper.setText(new String(text.getBytes(), "UTF-8"), true);

                    this.javamailsenderImpl.send(message);