0

まず、投稿された回答に感謝します。このサイトは素晴らしいです。第二に、私は問題を抱えており、数日検索してもまだわかりません.同じ問題を抱えている人がたくさん見つかりましたが、答えはありません. アプリ エンジンで実行されているアプリケーションに画像をアップロードし、画像を添付してメールを送信しようとしています。また、画像をアップロードするために 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>

サーブレットが応答する必要があるものを選択する 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 フォームとサーブレットができました。まず、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();
        }
    }

}
}
4

2 に答える 2

2

例#1の問題は、テキスト本文を設定してからマルチパートを追加しようとしている可能性があると思います。それは正しくありません。メッセージは、Content-Type: text/plainまたはContent-Type: multipart/mixedその両方である可能性があります。添付ファイルがある場合は、テキスト本文をマルチパートの 1 つとして追加する必要があります。このようなもの(テストされていません):

   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-実際のデータを使用する必要があります-文字列またはバイト[]など.

体の部分の概念を理解するために、メッセージの構造を視覚化してみてください。電子メール ヘッダーには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
于 2011-08-19T15:41:11.767 に答える
1

私はついにそれを働かせました。(もちろん)画像のアップロードの問題。バッファ内の同じバイトを上書きしていましたが、オフセットを考慮していませんでした。正しい方法は次のとおりです。

        int len=0;
        size=0;
        while ((len = stream.read(buffer, size,buffer.length)) != -1)
                {
                    size+=len;
                }
于 2011-08-19T18:05:44.267 に答える