使用java mail api从app引擎发送带有图像附件的电子邮件时出现问题

时间:2011-08-19 15:29:24

标签: google-app-engine servlets file-upload email-attachments

首先,我要感谢大家发布的答案。这个网站很棒。 第二,我遇到了问题,经过几天的搜索,我仍然无法弄明白。我发现很多人有同样的问题,但没有答案。 我正在尝试将图像上传到在app引擎上运行的应用程序,并发送包含图像作为附件的电子邮件。我也使用org.apache.commons.fileupload来上传图像。 我成功发送了电子邮件,但我在附件方面遇到了问题。 我的html表单如下所示:

<form id="contact" action="/sign" method="post" enctype="multipart/form-data">
                            <fieldset>
                                <label>Nume / Prenume</label>
                                <input type="text" name="nume" />
                                <label>Telefon</label>
                                <input type="text" name="telefon" />
                                <label>E-mail</label>
                                <input type="text" name="email"/>                                    
                            </fieldset>
                            <fieldset>
                                <label>Textul sesizarii</label>
                                <textarea name="textulses"></textarea>
                                <div class="upload-fix-wrap">
                                    <input size="35" class="upload" type="file"         name=myFile />
                                    <input type="text" />
                                    <button>Incarca poze</button>
                                </div>
                                <button class="send" type="submit">Trimite </button>
                            </fieldset>
                        </form>

我选择servlet应该回答的web.xml文件如下所示:

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
    <servlet-name>sign</servlet-name>
    <servlet-class>com.campiacareiului.CampiaCareiuluiServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>sign</servlet-name>
    <url-pattern>/sign</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

所以,到现在为止我有一个html表单和一个servlet来响应。 首先,我尝试使用javax.mail:

public class CampiaCareiuluiServlet extends HttpServlet {
private String nume=null;
private String telefon=null;
private String email=null;
private String textulses=null;
private String attname=null;
private  byte[] buffer = new byte[8192000];
private boolean att=false;
private int size=0;
private static final Logger log =
          Logger.getLogger(CampiaCareiuluiServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    try {

        ServletFileUpload upload=new ServletFileUpload();
        FileItemIterator it = upload.getItemIterator(req);
        while(it.hasNext()){
            FileItemStream item = it.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
    if(name.equals("nume")) nume=Streams.asString(stream);
        else if(name.equals("telefon")) telefon=Streams.asString(stream);
        else if(name.equals("email")) email=Streams.asString(stream);
        else if(name.equals("textulses")) textulses=Streams.asString(stream);
            } else {
                att=true;
                attname=item.getName();

                int len;
                size=0;
               while ((len = stream.read(buffer, 0, buffer.length)) != -1){
                    size+=len;

                 }

            }

        }
          Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

  String msgBody = "Nume/Prenume: "+nume+" Telefon: "+telefon+" Mail:"+email+"Textul  Sesizarii: "+textulses;
  Message msg = new MimeMessage(session);
                msg.setFrom(new     InternetAddress("myAdministratorAccount@gmail.com", ""));
                msg.addRecipient(Message.RecipientType.TO,
                                 new InternetAddress("aUser@yahoo.com", "Mr. User"));
                msg.setSubject("Mail Sesizare Campia Careiului");
                msg.setText(msgBody);
   if(att){
         byte[] bufferTemp = new byte[size];
         for(int i=0;i<=size;i++)
             bufferTemp[i]=buffer[i];
             Multipart mp=new MimeMultipart();
                   MimeBodyPart attachment= new MimeBodyPart();

                   DataSource src = new ByteArrayDataSource 
                           (bufferTemp,"image/jpeg"); 
                   attachment.setFileName(attname);
                   attachment.setContent(src,"image/jpeg"); 
                   mp.addBodyPart(attachment);
                   msg.setContent(mp);

         }
     Transport.send(msg);
     resp.sendRedirect("/contact.html");
    } catch (Exception ex) {
          try {
            throw new ServletException(ex);
        } catch (ServletException e) {

            e.printStackTrace();
}
      }

}
}

当我调试应用程序时,它显示它已将图像上传到缓冲区,但它无法发送邮件(没有抛出异常)。(我将应用程序上传到应用程序引擎,因为如果你是的话,你无法发送电子邮件在本地运行应用程序)。   接下来我尝试使用低级API。我所做的改变是:

                    Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            String msgBody = "Nume/Prenume: "+nume+" Telefon: "+telefon+" Mail: "+email+" Textul Sesizarii: "+textulses;

            MailService service = MailServiceFactory.getMailService(); 
            MailService.Message msg = new MailService.Message(); 
                    msg.setSender("myAdminAccount@gmail.com"); 
                    msg.setTo("aUser@yahoo.com"); 
                    msg.setSubject("Mail Sesizare Campia Careiului"); 
                    msg.setTextBody(msgBody); 
     if(att){
         byte[] bufferTemp = new byte[size];
         for(int i=0;i<=size;i++)
             bufferTemp[i]=buffer[i];

            MailService.Attachment attachment=new MailService.Attachment("picture.pdf",
                   bufferTemp);
            msg.setAttachments(attachment);
             }
            service.send(msg);
                            resp.sendRedirect("/contact.html");

现在,它发送带有附件的电子邮件,但是当我尝试从我的电子邮件帐户(pdf或图像)下载附件时,它无法识别它。它只是说该文件可能已经存在损坏。当我尝试发送图像时,我放了“image / jpeg”,当我尝试发送pdf时,我把“application / pdf”。  我到处搜索,我发现其他人有这个问题,但没有解决方案。如果有人能帮助我,我将不胜感激。 (我为我的拼写错误道歉) 我的进口是:

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.mail.Multipart;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.mail.MailService;
import com.google.appengine.api.mail.MailServiceFactory;

我已成功发送带有以下代码的附件的电子邮件。但我的问题是,当我尝试下载附件时,或者当我尝试查看它时,它说它已损坏且无法识别它。我认为问题在于上传图像。要上传图像我使用org.apache.commons.fileupload。 在这里,我将图像上传到字节数组:

    while ((len = stream.read(buffer, 0, buffer.length)) != -1)
           {
                size+=len;
            }

我还会以“尺寸”跟踪上传图片的尺寸 在这里,我将图像移动到另一个适当尺寸的缓冲区中:

            byte[] bufferTemp = new byte[size];
            for(int i=0;i<size;i++)
                bufferTemp[i]=buffer[i];

附件中的图片与上传的图片具有相同的尺寸,但在某种程度上已损坏。如果有人可以提供帮助。源代码是:

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.mail.Multipart;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;


@SuppressWarnings("serial")
public class CampiaCareiuluiServlet extends HttpServlet {
private String nume=null;
private String telefon=null;
private String email=null;
private String textulses=null;
private String attname=null;
private  byte[] buffer = new byte[8192000];
private boolean att=false;
private int size=0;
private static final Logger log =
        Logger.getLogger(CampiaCareiuluiServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    try {

        ServletFileUpload upload=new ServletFileUpload();
        FileItemIterator it = upload.getItemIterator(req);
        while(it.hasNext()){
            FileItemStream item = it.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                if(name.equals("nume")) nume=Streams.asString(stream);
                else if(name.equals("telefon")) telefon=Streams.asString(stream);
                else if(name.equals("email")) email=Streams.asString(stream);
                else if(name.equals("textulses")) textulses=Streams.asString(stream);
            } else {
                att=true;
                attname=item.getName();

                int len;
                size=0;
                while ((len = stream.read(buffer, 0, buffer.length)) != -1){
                    size+=len;

                }

            }

        }
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        String msgBody = "Nume/Prenume: "+nume+" Telefon: "+telefon+" Mail: "+email+" Textul Sesizarii: "+textulses;

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("ursu.adrian88@gmail.com", "gmail.com Adrian Ursu"));
        msg.addRecipient(Message.RecipientType.TO,
                new InternetAddress("ursu.adrian88@gmail.com", "Mr. User"));
        msg.setSubject("Mail Sesizare Campia Careiului");

        if(!att){
            msg.setText(msgBody);      
        }
        else{
            byte[] bufferTemp = new byte[size];
            for(int i=0;i<size;i++)
                bufferTemp[i]=buffer[i];

            Multipart mp=new MimeMultipart();

            MimeBodyPart textPart = new MimeBodyPart();
            textPart.setContent(msgBody, "text/plain");

            mp.addBodyPart(textPart);

            MimeBodyPart attachment= new MimeBodyPart();
            DataSource src = new ByteArrayDataSource 
                    (bufferTemp, "image/jpeg"); 
            attachment.setFileName(attname);    
            attachment.setDataHandler(new DataHandler 
                    (src));
            mp.addBodyPart(attachment);
            msg.setContent(mp);
            msg.saveChanges();



        }
        Transport.send(msg);

        resp.sendRedirect("/contact.html");
    } catch (Exception ex) {
        try {
            throw new ServletException(ex);
        } catch (ServletException e) {

            e.printStackTrace();
        }
    }

}
}

2 个答案:

答案 0 :(得分:2)

我认为示例#1 中的问题可能是您正在设置文本正文然后尝试添加多部分。这是不正确的。邮件可以是Content-Type: text/plainContent-Type: multipart/mixed,但不能同时为 if (!att) { msg.setText(msgBody); } else { //first build and add the text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(msgBody, "text/plain"); Multipart mp=new MimeMultipart(); mp.addBodyPart(textPart)); //now read/buffer the image data (?) byte[] bufferTemp = new byte[size]; for(int i=0;i<=size;i++) bufferTemp[i]=buffer[i]; // YOU NEED TO FIX THIS!! } // now add the attachment part. // the attachment data must be added all together, not in pieces MimeBodyPart attachment= new MimeBodyPart(); // YOU NEED TO FIX THIS!! attachment.setFileName(attname); attachment.setContent(bufferTemp,"image/jpeg"); mp.addBodyPart(attachment); msg.setContent(mp); src。如果有附件,则需要将文本正文添加为多部分之一。像这样(未经测试):

attachment

您在阅读图片数据时的方式也存在问题,但是您没有提供足够的代码告诉您如何更正它。在将其添加到正文部分内容之前,您需要将ENTIRE图像数据读入某个对象(数组,缓冲区等)。并且您无法添加Content-type: multipart/mixed作为Content-type: text/plain的内容 - 您必须使用实际数据 - 字符串或字节[]等。

为了帮助理解身体部位的概念,尝试并可视化消息的结构。电子邮件标题列出Content-type: image/jpeg标题,其中包含To: testuser@test.com From: testuser2@test.com Date: Aug 19, 2011 Content-Type: multipart/mixed; boundary="aswevb323f23f3f" This is a message with multiple parts in MIME format. --aswevb323f23f3f Content-Type: text/plain This is the body of the message. --aswevb323f23f3f Content-Type: image/jpeg Content-Transfer-Encoding: base64 ZQs0bWw+CiAgPGhlYWQ+CiAgP49oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg Ym9keSBvZiB0aGUgbWVzc2FnZa48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg== --aswevb323f23f3f 和{{1}}的附加内容。

{{1}}

答案 1 :(得分:1)

我终于开始工作了。问题(当然)上传图像。我在覆盖缓冲区中的相同字节,我没有考虑到偏移量。正确的方法是:

        int len=0;
        size=0;
        while ((len = stream.read(buffer, size,buffer.length)) != -1)
                {
                    size+=len;
                }