Sending HTML as attachment

Hello,
I am getting
java.io.IOException: stream is closed
when I run the following code:
import java.io.*;
import java.net.*;   
import javax.mail.*;  
import javax.mail.Authenticator; 
import javax.mail.internet.*;   
import javax.activation.*;       
public class SendApp2
    public static void send(String from, String to, String CC, String BCC, String subject, String content)
    throws AddressException, MessagingException, Exception    
        String smtpHost = "127.0.0.1";
        int smtpPort = 25;
          // Create a mail session           
        java.util.Properties props = new java.util.Properties();           
        props.put("mail.smtp.host", smtpHost);           
        props.put("mail.smtp.port", ""+smtpPort); 
        props.put("mail.smtp.auth", "true");
        Authenticator auth = new SimpleAuthenticator();               
        Session session = Session.getInstance(props, auth); 
        // Construct the message
        Message msg = new MimeMessage(session);     
        msg.setFrom(new InternetAddress(from));    
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        if (!CC.equals(""))
        msg.setRecipient(Message.RecipientType.CC, new InternetAddress(CC)); 
        if(!BCC.equals(""))
        msg.setRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
        URL url = new URL("http://www.sitelogic.co.uk/index.jsp");
        URLConnection con = url.openConnection();
        InputStream in = con.getInputStream();
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText("test");
        MailDataSource mailDS = new MailDataSource("text/html", in);
        mbp.setDataHandler(new DataHandler(mailDS));
        mbp.setFileName("test.html");
        mbp.setHeader("Content-ID","text/html");
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText("test");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        msg.setSubject(subject);
        msg.setText(content);
        msg.setContent(mp); // **********added
        // Send the message
        Transport.send(msg);       
}The MailDataSource code:
import javax.activation.DataSource;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.*;
public class MailDataSource implements DataSource
    InputStream contentStream = null;
    OutputStream os;
    String mimeType = null;
    String name = null;
    public MailDataSource (String mimeType, InputStream is) throws Exception
        this.contentStream = is;  
        this.mimeType = mimeType;       
    public String getContentType ()
        return this.mimeType;
    public InputStream getInputStream ()
        return this.contentStream;
    public String getName ()
        return name;
    public OutputStream getOutputStream ()
        return os;
}Any help appreciated, thanks

Why aren't you using URLDataSource?Because I didnt know about it :-)
I found a much simpler way to do it with URLDataSource, thanks for the tip.

Similar Messages

  • Send HTML as attachment in email in Stored Procedure

    Hi Guys,
    I am writing a stored procedure to send HTML attachment. Below is my code but no html attachment sent in mail. Kindly advise.
    USE [CarsemERP]
    GO
    /****** Object: StoredProcedure [dbo].[DBA_CarsemERP_SQLBlocks] Script Date: 04/01/2015 15:14:15 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author: <THARMENDRAN>
    -- Create date: <2014FEB21>
    -- Description: TO CHECK ANY LOCKS MORE THN 20 SEC IN SQL SERVER
    -- =============================================
    ALTER PROCEDURE [dbo].[DBA_CarsemERP_SQLBlocks]
    AS
    BEGIN
    DECLARE @iCnt As Int
    DECLARE @ICnt2 As Int
    DECLARE @SendEmail AS VARCHAR(3)
    DECLARE @Temp_DetailReq1 TABLE (
    idx smallint Primary Key IDENTITY(1,1),
    DBName varchar(30), RequestId Int, BlockingId Int, BlockedObjectName varchar(30),LockType varchar(30), RequestingText varchar(max), BlockingText varchar(max),
    LoginName varchar (30), HostName varchar (30))
    DECLARE @Temp_DetailReq2 TABLE (
    idx smallint Primary Key IDENTITY(1,1),
    DBName varchar(30), RequestId Int, BlockingId Int, BlockedObjectName varchar(30),LockType varchar(30), RequestingText varchar(max), BlockingText varchar(max),
    LoginName varchar (30), HostName varchar (30))
    SET @SendEmail = 'NO'
    SELECT @iCnt= COUNT(*) FROM DBA_SQLBlocksViewTharmen
    IF @iCnt > 0
    BEGIN
    Insert Into @Temp_DetailReq1
    Select DBName, request_session_id, blocking_session_id, BlockedObjectName,resource_type, RequestingText, BlockingTest, LoginName, HostName From DBA_SQLBlocksViewTharmen
    END
    WAITFOR DELAY '00:00:20'
    select @iCnt2= COUNT(*) FROM DBA_SQLBlocksViewTharmen
    IF @iCnt2 > 0
    BEGIN
    DECLARE @columnHeaders NVARCHAR(MAX)
    DECLARE @tableHTML NVARCHAR(MAX)
    DECLARE @body NVARCHAR(MAX)
    Insert Into @Temp_DetailReq2
    Select DBName, request_session_id, blocking_session_id, BlockedObjectName,resource_type, RequestingText, BlockingTest, LoginName, HostName From DBA_SQLBlocksViewTharmen
    SET @SendEmail = 'YES'
    BEGIN
    SET @columnHeaders = 'DBName</th><th>RequestId</th><th>BlockingId</th><th>BlockedObjectName</th><th>LockType</th><th>RequestingText</th><th>BlockingText</th><th>LoginName</th><th>HostName'
    set @tableHTML =
    '<div><b>There is blocking in VERPSVR02-02.</b></div><br>' + -- This is the bold text at the top of your email
    '<table border="0" cellpadding="5"><font face="Calibri" size=2>' +
    '<tr><th>' + @columnHeaders + '</th></tr>' +
    convert(nvarchar(max),
    select td = [DBName], '', -- Here we put the column names
    td = [RequestId], '',
    td = [BlockingId], '',
    td = [BlockedObjectName], '',
    td = [LockType], '',
    td = [RequestingText], '',
    td = [BlockingText], '',
    td = [LoginName], '',
    td = [HostName], '' -- Here we put the column names
    from @Temp_DetailReq2
    for xml path('tr'), type)) +'</font></table>'
    END
    END
    IF @SendEmail = 'YES'
    BEGIN
    EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'MyDBMailProfileName',
    @recipients = '[email protected]',
    @body = 'Please refer the attachment' ,
    @body_format = 'HTML',
    @subject = 'Alert! Blocking On ERPSVR02-02 Live Server',
    @file_attachments = @tableHTML,
    @importance = 'High';
    END
    END

    Hi Guys,
    I need help on how to generated HTML as attachment to email. I have write below stored procedure but the html did not send as attachment. Kindly guide me on how to save the generated HTML as a file and send it as attachment.
    USE [CarsemERP]
    GO
    /****** Object: StoredProcedure [dbo].[DBA_CarsemERP_SQLBlocks] Script Date: 04/01/2015 15:14:15 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    -- =============================================
    -- Author: <THARMENDRAN>
    -- Create date: <2014FEB21>
    -- Description: TO CHECK ANY LOCKS MORE THN 20 SEC IN SQL SERVER
    -- =============================================
    ALTER PROCEDURE [dbo].[DBA_CarsemERP_SQLBlocks]
    AS
    BEGIN
    DECLARE @iCnt As Int
    DECLARE @ICnt2 As Int
    DECLARE @SendEmail AS VARCHAR(3)
    DECLARE @Temp_DetailReq1 TABLE (
    idx smallint Primary Key IDENTITY(1,1),
    DBName varchar(30), RequestId Int, BlockingId Int, BlockedObjectName varchar(30),LockType varchar(30), RequestingText varchar(max), BlockingText varchar(max),
    LoginName varchar (30), HostName varchar (30))
    DECLARE @Temp_DetailReq2 TABLE (
    idx smallint Primary Key IDENTITY(1,1),
    DBName varchar(30), RequestId Int, BlockingId Int, BlockedObjectName varchar(30),LockType varchar(30), RequestingText varchar(max), BlockingText varchar(max),
    LoginName varchar (30), HostName varchar (30))
    SET @SendEmail = 'NO'
    SELECT @iCnt= COUNT(*) FROM DBA_SQLBlocksViewTharmen
    IF @iCnt > 0
    BEGIN
    Insert Into @Temp_DetailReq1
    Select DBName, request_session_id, blocking_session_id, BlockedObjectName,resource_type, RequestingText, BlockingTest, LoginName, HostName From DBA_SQLBlocksViewTharmen
    END
    WAITFOR DELAY '00:00:20'
    select @iCnt2= COUNT(*) FROM DBA_SQLBlocksViewTharmen
    IF @iCnt2 > 0
    BEGIN
    DECLARE @columnHeaders NVARCHAR(MAX)
    DECLARE @tableHTML NVARCHAR(MAX)
    DECLARE @body NVARCHAR(MAX)
    Insert Into @Temp_DetailReq2
    Select DBName, request_session_id, blocking_session_id, BlockedObjectName,resource_type, RequestingText, BlockingTest, LoginName, HostName From DBA_SQLBlocksViewTharmen
    SET @SendEmail = 'YES'
    BEGIN
    SET @columnHeaders = 'DBName</th><th>RequestId</th><th>BlockingId</th><th>BlockedObjectName</th><th>LockType</th><th>RequestingText</th><th>BlockingText</th><th>LoginName</th><th>HostName'
    set @tableHTML =
    '<div><b>There is blocking in VERPSVR02-02.</b></div><br>' + -- This is the bold text at the top of your email
    '<table border="0" cellpadding="5"><font face="Calibri" size=2>' +
    '<tr><th>' + @columnHeaders + '</th></tr>' +
    convert(nvarchar(max),
    select td = [DBName], '', -- Here we put the column names
    td = [RequestId], '',
    td = [BlockingId], '',
    td = [BlockedObjectName], '',
    td = [LockType], '',
    td = [RequestingText], '',
    td = [BlockingText], '',
    td = [LoginName], '',
    td = [HostName], '' -- Here we put the column names
    from @Temp_DetailReq2
    for xml path('tr'), type)) +'</font></table>'
    END
    END
    IF @SendEmail = 'YES'
    BEGIN
    EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'MyDBMailProfileName',
    @recipients = '[email protected]',
    @body = 'Please refer the attachment' ,
    @body_format = 'HTML',
    @subject = 'Alert! Blocking On ERPSVR02-02 Live Server',
    @file_attachments = @tableHTML,
    @importance = 'High';
    END
    END

  • HTML file send as an attachment via an email adapter

    Hi,
    I need to implement an scenario File -> XI -> Email (html attachment) . To send html as attachment , do i need to go for XSLT mapping ? ...please share your ideas if any ..
    Regards
    Vinay P.

    Hi Vinay,
    Have you seen this blog?
    http://www.sdn.sap.com/irj/scn/weblogs;jsessionid=%28J2EE3414900%29ID1832422350DB01827388014243714513End?blog=/pub/wlg/6321
    Regards
    Suraj

  • To Send HTML Format and excel file attachment  in same mail

    Dear All,
            Have requerment ,to send a mail options HTML table format and same data in excel file attachement.have capable to do the html format using methods BCS .but how to send excel format attachment in same  mail.
    Please guide me how to do it.
    Regards ,
    Santhu
    Edited by: santosh jajur on Apr 9, 2010 1:54 PM

    Santhosh,
    please check the code:
    report bcs_example_7.
    This report provides an example for sending an Excel
    attachment in Unicode Systems
    constants:
      gc_tab  type c value cl_bcs_convert=>gc_tab,
      gc_crlf type c value cl_bcs_convert=>gc_crlf.
    parameters:
      mailto type ad_smtpadr
       default 'ur mail id'.                    "#EC *
    data send_request   type ref to cl_bcs.
    data document       type ref to cl_document_bcs.
    data recipient      type ref to if_recipient_bcs.
    data bcs_exception  type ref to cx_bcs.
    data main_text      type bcsy_text.
    data binary_content type solix_tab.
    data size           type so_obj_len.
    data sent_to_all    type os_boolean.
    start-of-selection.
      perform create_content.
      perform send.
    form send.
      try.
          send_request = cl_bcs=>create_persistent( ).
        create document object from internal table with text
          append 'Hello world!' to main_text.                   "#EC NOTEXT
          document = cl_document_bcs=>create_document(
            i_type    = 'RAW'
            i_text    = main_text
            i_subject = 'Test Created By BCS_EXAMPLE_7' ).      "#EC NOTEXT
        add the spread sheet as attachment to document object
          document->add_attachment(
            i_attachment_type    = 'xls'                        "#EC NOTEXT
            i_attachment_subject = 'ExampleSpreadSheet'         "#EC NOTEXT
            i_attachment_size    = size
            i_att_content_hex    = binary_content ).
        add document object to send request
          send_request->set_document( document ).
        --------- add recipient (e-mail address) -----------------------
        create recipient object
          recipient = cl_cam_address_bcs=>create_internet_address( mailto ).
        add recipient object to send request
          send_request->add_recipient( recipient ).
        ---------- send document ---------------------------------------
          sent_to_all = send_request->send( i_with_error_screen = 'X' ).
          commit work.
          if sent_to_all is initial.
            message i500(sbcoms) with mailto.
          else.
            message s022(so).
          endif.
      endtry.
    endform.                    "send
    form create_content.
      data lv_string type string.
      data ls_t100 type t100.
    columns are separated by TAB and each line ends with CRLF
      concatenate 'This Is Just Example Text!'                  "#EC NOTEXT
                  gc_crlf gc_crlf
                  into lv_string.
    header line
      concatenate lv_string
                  'MSGID'    gc_tab
                  'MSGNO'    gc_tab
                  'Language' gc_tab                             "#EC NOTEXT
                  'Text'     gc_crlf                            "#EC NOTEXT
                  into lv_string.
    data lines
      select * from t100 into ls_t100
        where arbgb = 'SO' and msgnr = '182'.
        concatenate lv_string
                    ls_t100-arbgb gc_tab
                    ls_t100-msgnr gc_tab
                    ls_t100-sprsl gc_tab
                    ls_t100-text  gc_crlf
                    into lv_string.
      endselect.
      select * from t100 into ls_t100
        where arbgb = 'SO' and msgnr = '316'.
        concatenate lv_string
                    ls_t100-arbgb gc_tab
                    ls_t100-msgnr gc_tab
                    ls_t100-sprsl gc_tab
                    ls_t100-text  gc_crlf
                    into lv_string.
      endselect.
      try.
          cl_bcs_convert=>string_to_solix(
            exporting
              iv_string   = lv_string
              iv_codepage = '4103'  "suitable for MS Excel, leave empty
              iv_add_bom  = 'X'     "for other doc types
            importing
              et_solix  = binary_content
              ev_size   = size ).
        catch cx_bcs.
          message e445(so).
      endtry.
    endform.                    "create_content
    Thanks.

  • Send HTML attachment by email

    Hello everybody,
    I made a program to send by email an HTML file as attachment.  All works fine except that the HTML file is not attach to the mail, instead of that the HTML code is inserted in the email body.
    The same code works fine for XLS, PDF format, attachment is created, but not for HTM or TXT format.
    I'm in 4.6C. I think the problem is coming from the configuration of SAPConnect.
    Here is the routine code :
    *&      Form  send_mail
    *       Send mail
    *      -->PT_HTML  Attachment file containing HTML code
    *      -->PW_EMAIL Email address
    *      <--PW_RCODE Return code
    FORM send_mail TABLES   pt_html STRUCTURE w3html
                   USING    pw_email
                            pw_obj_descr
                   CHANGING pw_rcode.
      DATA : lt_file_att TYPE TABLE OF solisti1,
             ls_file_att TYPE solisti1.
      DATA : ls_document_data TYPE sodocchgi1,
             l_cnt   TYPE i.
      DATA : lt_packing_list  TYPE TABLE OF sopcklsti1,
             ls_packing_list  TYPE sopcklsti1,
             lt_contents      TYPE TABLE OF solisti1,
             ls_contents      TYPE solisti1,
             lt_receivers     TYPE TABLE OF somlreci1,
             ls_receivers     TYPE somlreci1,
             lt_object_header TYPE TABLE OF solisti1,
             ls_object_header TYPE solisti1.
      DATA : lt_objtxt TYPE TABLE OF solisti1   WITH HEADER LINE,
             l_lines TYPE i,
             l_sender TYPE so_rec_ext.
      CLEAR pw_rcode.
      lt_file_att[] = pt_html[].
    * Fill the document data and get size of attachment
      CLEAR ls_document_data.
      DESCRIBE TABLE lt_file_att LINES l_lines.
      READ TABLE lt_file_att INTO ls_file_att INDEX l_lines.
      ls_document_data-doc_size =
         ( l_lines - 1 ) * 255 + STRLEN( ls_file_att ).
      ls_document_data-obj_langu  = sy-langu.
      ls_document_data-obj_name   = 'Report to VMI'.
      ls_document_data-obj_descr  = pw_obj_descr.
      ls_document_data-sensitivty = 'F'.
    * Describe and create the body of the message
      CLEAR ls_packing_list.
      REFRESH lt_packing_list.
      ls_packing_list-transf_bin = space.
      ls_packing_list-head_start = 1.
      ls_packing_list-head_num = 0.
      ls_packing_list-body_start = 1.
      ls_packing_list-body_num = 1.
      ls_packing_list-doc_type = 'RAW'.
      APPEND ls_packing_list TO lt_packing_list.
    * Describe and create attachment
      CLEAR ls_packing_list.
      ls_packing_list-transf_bin = ' '.
      ls_packing_list-head_start = 1.
      ls_packing_list-head_num   = 0.
      ls_packing_list-body_start = 1.
      DESCRIBE TABLE lt_file_att LINES ls_packing_list-body_num.
      ls_packing_list-doc_type   =  'HTM'.
      ls_packing_list-obj_descr  =  'TEST1'.
      ls_packing_list-obj_name   =  'TEST1'.
      ls_packing_list-doc_size   =  ls_packing_list-body_num * 255.
      APPEND ls_packing_list TO lt_packing_list.
    * Add the recipient(s) email address
      CLEAR ls_receivers.
      REFRESH lt_receivers.
      ls_receivers-receiver = pw_email.
      ls_receivers-rec_type = 'U'.
      ls_receivers-com_type = 'INT'.
      ls_receivers-notif_del = 'X'.
      ls_receivers-notif_ndel = 'X'.
      APPEND ls_receivers TO lt_receivers.
      CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
           EXPORTING
                document_data              = ls_document_data
                put_in_outbox              = 'X'
                sender_address             = l_sender
                sender_address_type        = 'INT'
           TABLES
                packing_list               = lt_packing_list
                contents_txt               = lt_file_att
    *            contents_bin               = lt_file_att
                receivers                  = lt_receivers
           EXCEPTIONS
                too_many_receivers         = 1
                document_not_sent          = 2
                document_type_not_exist    = 3
                operation_no_authorization = 4
                parameter_error            = 5
                x_error                    = 6
                enqueue_error              = 7
                OTHERS                     = 8.
      pw_rcode = sy-subrc.
    ENDFORM.                    " send_mail
    Thank you in advance for your answer.

    hi,
    pls use this demo code and reward points if it works -
    REPORT  ZGILL_SENDMAIL_PDF                      .
    INCLUDE ZGILL_INCMAIL.  "SEE BELOW FOR INCLUDE PROGRAM CODE.
    DATA
    DATA : itab LIKE tline OCCURS 0 WITH HEADER LINE.
    DATA : file_name TYPE string.
    data : path like PCFILE-PATH.
    data : extension(5) type c.
    data : name(100) type c.
    SELECTION SCREEN
    PARAMETERS : receiver TYPE somlreci1-receiver lower case DEFAULT '[email protected]'.
    PARAMETERS : p_file LIKE rlgrap-filename
    OBLIGATORY DEFAULT 'C:\TEMP\SALARY_SLIP1.PDF'.
    AT SELECTION SCREEN
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR p_file.
    CLEAR p_file.
    CALL FUNCTION 'F4_FILENAME'
    IMPORTING
    file_name = p_file.
    START-OF-SELECTION
    START-OF-SELECTION.
    PERFORM ml_customize USING 'Tst' 'Testing'.
    PERFORM ml_addrecp USING receiver 'U'.
    PERFORM upl.
    PERFORM doconv TABLES itab objbin.
    PERFORM ml_prepare USING 'X' extension name.
    PERFORM ml_dosend.
    SUBMIT rsconn01
    WITH mode EQ 'INT'
    AND RETURN.
    FORM
    FORM upl.
    file_name = p_file.
    CALL FUNCTION 'GUI_UPLOAD'
    EXPORTING
    filename = file_name
    filetype = 'BIN'
    TABLES
    data_tab = itab
    EXCEPTIONS
    file_open_error = 1
    file_read_error = 2
    no_batch = 3
    gui_refuse_filetransfer = 4
    invalid_type = 5
    no_authority = 6
    unknown_error = 7
    bad_data_format = 8
    header_not_allowed = 9
    separator_not_allowed = 10
    header_too_long = 11
    unknown_dp_error = 12
    access_denied = 13
    dp_out_of_memory = 14
    disk_full = 15
    dp_timeout = 16
    OTHERS = 17.
    path = file_name.
    CALL FUNCTION 'PC_SPLIT_COMPLETE_FILENAME'
    EXPORTING
    complete_filename = path
    CHECK_DOS_FORMAT =
    IMPORTING
    DRIVE =
    EXTENSION = extension
    NAME = name
    NAME_WITH_EXT =
    PATH =
    EXCEPTIONS
    INVALID_DRIVE = 1
    INVALID_EXTENSION = 2
    INVALID_NAME = 3
    INVALID_PATH = 4
    OTHERS = 5
    ENDFORM. "upl
    *********************iNCLUDE pROGRAM********************************************
    *&  Include           ZGILL_INCMAIL                                    *
    Data
    DATA: docdata LIKE sodocchgi1,
    objpack LIKE sopcklsti1 OCCURS 1 WITH HEADER LINE,
    objhead LIKE solisti1 OCCURS 1 WITH HEADER LINE,
    objtxt LIKE solisti1 OCCURS 10 WITH HEADER LINE,
    objbin LIKE solisti1 OCCURS 10 WITH HEADER LINE,
    objhex LIKE solix OCCURS 10 WITH HEADER LINE,
    reclist LIKE somlreci1 OCCURS 1 WITH HEADER LINE.
    DATA: tab_lines TYPE i,
    doc_size TYPE i,
    att_type LIKE soodk-objtp.
    DATA: listobject LIKE abaplist OCCURS 1 WITH HEADER LINE.
    FORM
    FORM ml_customize USING objname objdesc.
    Clear Variables
    CLEAR docdata.
    REFRESH objpack.
    CLEAR objpack.
    REFRESH objhead.
    REFRESH objtxt.
    CLEAR objtxt.
    REFRESH objbin.
    CLEAR objbin.
    REFRESH objhex.
    CLEAR objhex.
    REFRESH reclist.
    CLEAR reclist.
    REFRESH listobject.
    CLEAR listobject.
    CLEAR tab_lines.
    CLEAR doc_size.
    CLEAR att_type.
    Set Variables
    docdata-obj_name = objname.
    docdata-obj_descr = objdesc.
    ENDFORM. "ml_customize
    FORM
    FORM ml_addrecp USING preceiver prec_type.
    CLEAR reclist.
    reclist-receiver = preceiver.
    reclist-rec_type = prec_type.
    APPEND reclist.
    ENDFORM. "ml_customize
    FORM
    FORM ml_addtxt USING ptxt.
    CLEAR objtxt.
    objtxt = ptxt.
    APPEND objtxt.
    ENDFORM. "ml_customize
    FORM
    FORM ml_prepare USING bypassmemory whatatt_type whatname.
    IF bypassmemory = ''.
    Fetch List From Memory
    CALL FUNCTION 'LIST_FROM_MEMORY'
    TABLES
    listobject = listobject
    EXCEPTIONS
    OTHERS = 1.
    IF sy-subrc <> 0.
    MESSAGE ID '61' TYPE 'E' NUMBER '731'
    WITH 'LIST_FROM_MEMORY'.
    ENDIF.
    CALL FUNCTION 'TABLE_COMPRESS'
    IMPORTING
    COMPRESSED_SIZE =
    TABLES
    in = listobject
    out = objbin
    EXCEPTIONS
    OTHERS = 1
    IF sy-subrc <> 0.
    MESSAGE ID '61' TYPE 'E' NUMBER '731'
    WITH 'TABLE_COMPRESS'.
    ENDIF.
    ENDIF.
    Header Data
    Already Done Thru FM
    Main Text
    Already Done Thru FM
    Packing Info For Text Data
    DESCRIBE TABLE objtxt LINES tab_lines.
    READ TABLE objtxt INDEX tab_lines.
    docdata-doc_size = ( tab_lines - 1 ) * 255 + STRLEN( objtxt ).
    CLEAR objpack-transf_bin.
    objpack-head_start = 1.
    objpack-head_num = 0.
    objpack-body_start = 1.
    objpack-body_num = tab_lines.
    objpack-doc_type = 'TXT'.
    APPEND objpack.
    Packing Info Attachment
    att_type = whatatt_type..
    DESCRIBE TABLE objbin LINES tab_lines.
    READ TABLE objbin INDEX tab_lines.
    objpack-doc_size = ( tab_lines - 1 ) * 255 + STRLEN( objbin ).
    objpack-transf_bin = 'X'.
    objpack-head_start = 1.
    objpack-head_num = 0.
    objpack-body_start = 1.
    objpack-body_num = tab_lines.
    objpack-doc_type = att_type.
    objpack-obj_name = 'ATTACHMENT'.
    objpack-obj_descr = whatname.
    APPEND objpack.
    Receiver List
    Already done thru fm
    ENDFORM. "ml_prepare
    FORM
    FORM ml_dosend.
    CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
    EXPORTING
    document_data = docdata
    put_in_outbox = 'X'
    commit_work = 'X' "used from rel. 6.10
    IMPORTING
    SENT_TO_ALL =
    NEW_OBJECT_ID =
    TABLES
    packing_list = objpack
    object_header = objhead
    contents_bin = objbin
    contents_txt = objtxt
    CONTENTS_HEX = objhex
    OBJECT_PARA =
    object_parb =
    receivers = reclist
    EXCEPTIONS
    too_many_receivers = 1
    document_not_sent = 2
    document_type_not_exist = 3
    operation_no_authorization = 4
    parameter_error = 5
    x_error = 6
    enqueue_error = 7
    OTHERS = 8
    IF sy-subrc <> 0.
    MESSAGE ID 'SO' TYPE 'S' NUMBER '023'
    WITH docdata-obj_name.
    ENDIF.
    ENDFORM. "ml_customize
    FORM
    FORM ml_spooltopdf USING whatspoolid.
    DATA : pdf LIKE tline OCCURS 0 WITH HEADER LINE.
    Call Function
    CALL FUNCTION 'CONVERT_OTFSPOOLJOB_2_PDF'
    EXPORTING
    src_spoolid = whatspoolid
    TABLES
    pdf = pdf
    EXCEPTIONS
    err_no_otf_spooljob = 1
    OTHERS = 12.
    Convert
    PERFORM doconv TABLES pdf objbin.
    ENDFORM. "ml_spooltopdf
    FORM
    FORM doconv TABLES
    mypdf STRUCTURE tline
    outbin STRUCTURE solisti1.
    Data
    DATA : pos TYPE i.
    DATA : len TYPE i.
    Loop And Put Data
    LOOP AT mypdf.
    pos = 255 - len.
    IF pos > 134. "length of pdf_table
    pos = 134.
    ENDIF.
    outbin+len = mypdf(pos).
    len = len + pos.
    IF len = 255. "length of out (contents_bin)
    APPEND outbin.
    CLEAR: outbin, len.
    IF pos < 134.
    outbin = mypdf+pos.
    len = 134 - pos.
    ENDIF.
    ENDIF.
    ENDLOOP.
    IF len > 0.
    APPEND outbin.
    ENDIF.
    ENDFORM. "doconv
    **********************INCLUDE END********************************

  • Can i use HTML tag in text when sending contens as "Attachement(PDF)".

    Hi all!!
    i try to add html tag on ibot email text column.
    is it possible?
    - in ibot delivery content.
    send content as Attachment(PDF)
    "if sent as attachement, include this text" <--- mark this field
    and below multi line input column, can i use html tag, for example,
    Yahoo
    thanks in advance.
    Edited by: vingorius on 2010. 10. 31 오후 7:27

    hi vingorius ,
    No you cant include html but u can use variables
    To add a variable in a text message to provide context for the iBot attachment
    1. Click the following option:
    If sent as attachment, include this text
    2. Type the text into the text box with a session variable, a repository variable, or a presentation variable using the syntax shown in the following table:
    Variable Type
    Syntax
    Repository @{Variable_Name}
    Session @{NQ_SESSION.Variable_Name}
    Presentation @{Variable_Name}
    For example, Dear, @{NQ_SESSION.Variable_Name}, here is your personalized Weekly Sales Territory Update.
    NOTE: If you want to use the @ character, you need to precede it with the \ (back slash) character to separate it from the variable syntax. For example, Dear @{NQ_SESSION.DISPLAYNAME}, \@ New York, appears as Dear Joe Smith, @ New York.
    Source : BI Guide
    Thanks,
    Saichand.v

  • Wants to send html as inline message instead of attachment(without MTOM)

    Hi,
    We have reuirement want send html as inile message instead of attachemnt in OSB 11g with out MTOM.
    Any pointers on this regard will be of great help.
    Regards
    Venkata

    For example use WSDL like this:
    http://axis.apache.org/axis2/java/core/docs/mtom-guide.html#a251
    and don't forget to disable MTOM/XOP support for proxy and business service.
    You don't need anything but a base64binary element in your request or response message. That's all. When you turn MTOM/XOP support off, binary data will be inlined.
    If you will still face an issue, try to send your WSDL, describe input, output and your proxy flow.

  • How to send HTML as message body using SMTP

    I need to send HTML formatted emails. I used the Report Generation Toolkit to build my HTML document and make sure I had all of the formatting right. Then I modified the Save Report To File.vi to also give me the HTML text string on an output connector and I wire this string to the message input on the SMTP Email Send Message.vi.
    I receive the email OK, but all I see is the HTML code in the message body. What can I do to make sure that the email displays the message correctly.
    I use Outlook and I know it will receive and display HTML emails, I get them all the time.
    I would appreciate any help.

    Hi Dgw,
    it is similar. You must change message MINE content-type to "text/html" type. Because everyone document in email protocol have set MINE content-type. It is inforamtion for email servers and for email cients (Thunderbird, Outlook and etc.)
    For sendning mail with attachments you must use and modified "SMTP Send Multiple Attachments.vi" - if you can do backup of this VI and subVIs. Open Diagram of "SMTP Send Multiple Attachments.vi" after "SMTP Send Multiple
    Attachments Message.vi" and ther is VI "MIME Send Data Attachment.vi" - have control "MIME content-type" but code from NI don't use it.
    And like as my previous message, create new string control "MINE content-type" and take out this control to "main" Email VI.
    And embedd
    ed file you set up in control-cluster "attachments". I don't test it, but I mind thet must working :-)
    Have nice day
    JCC
    Attachments:
    email.jpg ‏70 KB

  • How to send html email notification in bpel

    hi gurus,
    i want to send html email notification from bpel.
    before, i already successful send html email with attachment, but when i send an email without attachment, then the body message will turn into a plain text.
    as i check from the email accepted, email with attachment will have a mime type "text/html" but if no attachment then it will be "text/plain"
    from the bpel configuration, by default the mime type already set to "text/html; charset=UTF-8", below is the sample configuration in my bpel process
    [quote]
    <copy>
                                    <from>string('text/html; charset=UTF-8')</from>
                                    <to variable="varNotificationReq"
                                        part="EmailPayload">
                                        <query>ns10:Content/ns10:MimeType</query>
                                    </to>
                                </copy>
    [/quote]
    i think this suppose to be a easy configuration, but i'm not sure whether i miss something in configuration the email process or this is a bugs in bpel.
    environment:
    linux
    jdev 11.1.1.6
    do u guys ever facing a same problem or have a solution to this ? please throw some light.
    thanks
    ===
    update, i found a temporary solutions.
    so i add a attachment from the process design, and then i change it from the source.
    [quote]
    <copy>
                                    <from>
                                        <literal>
                                            <Content xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService">
                                                <MimeType xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService">multipart/alternative</MimeType>
                                                <ContentBody xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService">
                                                    <MultiPart xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService">
                                                        <BodyPart xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService">
                                                            <MimeType xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/>
                                                            <ContentBody xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/>
                                                            <BodyPartName xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/>
                                                        </BodyPart>                                            
                                                    </MultiPart>
                                                </ContentBody>
                                            </Content>
                                        </literal>
                                    </from>
                                    <to variable="varNotificationReq"
                                        part="EmailPayload">
                                        <query>ns10:Content</query>
                                    </to>
                                </copy>
    <copy>
                                    <from>string('text/html; charset=UTF-8')</from>
                                    <to variable="varNotificationReq"
                                        part="EmailPayload">
                                        <query>ns10:Content/ns10:ContentBody/ns10:MultiPart/ns10:BodyPart[1]/ns10:MimeType</query>
                                    </to>
                                </copy>
                                <copy>
                                    <from>string('your message')</from>
                                    <to variable="varNotificationReq"
                                        part="EmailPayload">
                                        <query>ns10:Content/ns10:ContentBody/ns10:MultiPart/ns10:BodyPart[1]/ns10:ContentBody</query>
                                    </to>
                                </copy>
    [/quote]
    make sure you put the mime type multipart/alternative into the email payload content. by default, when you add attachment, it will generate mime type multipart mixed automatically.
    if you don't change it to multipart/alternative, your email will show a attachment, but actually your email doesn't contain any attachment.
    and then for the message and mimetype make sure you have that ns10:bodypart, because this email already been set as a multipart email.
    when you add attachment, by default it will generate 2 body part, first one is for the body message and the second one is for the attachment. since i only want to use the body message only, then i have to erase the second bodypart
    with this workaround, i can send a html email without attachment perfectly.
    but i have to take note, when i updating the email process from process design, then the source will be generated again automatically, and the edited one will be replaced.
    thanks.

    Make sure you upload all of the images used in your email to a server you control. Then, change your image paths to point to those uploaded images with absolute links.
    You will get marked as spam if you attempt to send images as attachments to a large list of recipients and most email clients won't download images to begin with, so make sure your html email makes sense with broken pictures.
    CSS support is spotty across email clients, if you use css, make sure it's inline, not embedded in the <head> or externally linked in the <head>. Some email clients strip out the <head> section entirely.
    Basically, you need to design your html email as if you haven't moved out of the 90's yet, as far as web design is concerned, in order to get maximum cross client compatibility.
    Then, when you're ready, I would suggest using a service like www.icontact.com or www.constantcontact.com if your subscriber list is anywhere over 100 or so recipients.

  • Send  XML as attachment in Email activity

    Hi
    My requirement is to send XML as an attachment through email .
    In the attachment if i select the MIME type as "XML" then no email notification is sent,
    but if i select the MIME type as "text/html" , then attachement is sent through email , but attachment is in different format( with no content inside attachment) .
    Can anyone help me on this .

    have you tried the example on this page : http://java.net/projects/oraclesoasuite11g/pages/Notification

  • E61 doesn't display cyrillic HTML email attachment...

    Nokia E61 build-in email client correctly recognizes all Russian encodings in plain-text email messages. But if the message contains HTML attachment written in Russian, E61 fails to display it properly - what I get is just a garbage of ISO-8859-1 accentuated symbols; looks like E61 fails to parse and recognize encoding parameters in MIME boundaries.
    Heres a short example (fragment of headers and message body that is being displayed incorrectly). Note that it's completely OK with the subject, the problem is only with the body.
    Subject: =?KOI8-R?B?ySDQz9PMxcTOycog1MXT1CDTIEdNQUlM?=
    MIME-Version: 1.0
    Content-Type: multipart/alternative;
    boundary="----=_Part_174591_13183675.1166271570659"
    ------=_Part_174591_13183675.1166271570659
    Content-Type: text/plain; charset=KOI8-R; format=flowed
    Content-Transfer-Encoding: base64
    Content-Disposition: inline
    xd3FIM/Eyc4g1MXT1CDQydPYzcEg1yBIVE1MLcbP0s3B1MUK
    ------=_Part_174591_13183675.1166271570659
    Content-Type: text/html; charset=KOI8-R
    Content-Transfer-Encoding: base64
    Content-Disposition: inline
    xd3FIM/Eyc4g1MXT1CA8c3BhbiBzdHlsZT0iZm9udC1zdHlsZTogaXRhbGljOyI+0MnT2M3BINcg
    SFRNTC3Gz9LNwdTFPC9zcGFuPjxicj4K
    ------=_Part_174591_13183675.1166271570659--

    Would you please provide me the any other way to attach a UTF-8 encoded file. Since I noticed that the (.html) file attachement that I am sending along with the mail is not UTF-8 encoded.
    This is the reason why the same html markup text (along with the non ASCII) characters are rendered correctly(in all browsers), when I was using an external UTF-8 Editor (gedit) and saved the .html file in UTF-8 format.
    Edited by: aspdeepak_prasanna on Aug 11, 2010 10:54 PM

  • Sending an Excel Attachment in E-mail, where linesize 255 characters

    Hi,
    I have a requirement where I need to send an Excel attachment of around 150 columns and the line-size is around 2000 characters.
    I was planning to use SO_DOCUMENT_SEND_API1.
    But, it appears that because of the restriction of 255 characters as SOLISTI1 structure has the field size of 255 characters.
    Please note, I cannot use any of the OLE or foreground Excel functions, as the job runs in the background.
    Please let me know if you have any solutions or work around.
    Hoiping to hear from all of the experts out there.
    Regards,
    Ani

    try to use the following classes :       
    send_request  TYPE REF TO cl_bcs,
            document      TYPE REF TO cl_document_bcs,
            conlengths    TYPE        so_obj_len,
            html          TYPE STANDARD TABLE OF w3html,
            sender_id     TYPE REF TO if_sender_bcs,
            recipient     TYPE REF TO if_recipient_bcs,
            sent_to_all   TYPE        os_boolean,
            bcs_exception TYPE REF TO cx_bcs,
            bcs_message   TYPE        string.

  • How to send email with attachment

    Hi friends,
    I am using soa 11.1.1.7.0
    Jdev 11.1.1.7.0
    WebLogic:- 10.3
    I want to generated email with attachment in BPEL 11g. Below is what i did in my bpel process
    Create simple hello world bpel process.
    In email activity below details are given
    <scope name="Email1">
    <bpelx:annotation>
    <bpelx:pattern patternName="bpelx:email"></bpelx:pattern>
    </bpelx:annotation>
       <variables>
       <variable name="varNotificationReq"
                              messageType="ns1:EmailNotificationRequest"/>
                    <variable name="varNotificationResponse"
                              messageType="ns1:ArrayOfResponse"/>
                    <variable name="NotificationServiceFaultVariable"
                              messageType="ns1:NotificationServiceErrorMessage"/>
                </variables>
                <sequence name="Sequence1">
                    <assign name="EmailParamsAssign">
                        <copy>
                            <from expression="string('Default')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:FromAccountName"/>
                        </copy>
                        <copy>
                            <from expression="string('')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:FromUserName"/>
                        </copy>
                        <copy>
                            <from expression="string('')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Bcc"/>
                        </copy>
                        <copy>
                            <from expression="string('')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Cc"/>
                        </copy>
                        <copy>
                            <from expression="string('')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:ReplyToAddress"/>
                        </copy>
                        <copy>
                            <from expression="bpws:getVariableData('inputVariable','payload','/client:process/client:subject')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Subject"/>
                        </copy>
                        <copy>
                            <from expression="bpws:getVariableData('inputVariable','payload','/client:process/client:to')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:To"/>
                        </copy>
                        <copy>
                            <from><Content xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"><MimeType xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService">multipart/mixed</MimeType><ContentBody xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"><MultiPart xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"> <BodyPart xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"><MimeType xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/><ContentBody xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/><BodyPartName xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/></BodyPart> <BodyPart xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"><MimeType xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/><ContentBody xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/><BodyPartName xmlns="http://xmlns.oracle.com/ias/pcbpel/NotificationService"/></BodyPart></MultiPart></ContentBody></Content></from>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Content"/>
                        </copy>
                        <copy>
                            <from expression="string('text/html; charset=UTF-8')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Content/ns1:ContentBody/ns1:MultiPart/ns1:BodyPart[1]/ns1:MimeType"/>
                        </copy>
                        <copy>
                            <from expression="bpws:getVariableData('inputVariable','payload','/client:process/client:body')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Content/ns1:ContentBody/ns1:MultiPart/ns1:BodyPart[1]/ns1:ContentBody"/>
                        </copy>
                        <copy>
                            <from expression="string('text/plain')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Content/ns1:ContentBody/ns1:MultiPart/ns1:BodyPart[2]/ns1:MimeType"/>
                        </copy>
                        <copy>
                            <from expression="string('SampleStudent.txt')"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Content/ns1:ContentBody/ns1:MultiPart/ns1:BodyPart[2]/ns1:BodyPartName"/>
                        </copy>
                        <copy>
                            <from expression="concat('file:///', bpws:getVariableData('inputVariable','payload','/client:process/client:attachmentURI'))"/>
                            <to variable="varNotificationReq" part="EmailPayload"
                                query="/EmailPayload/ns1:Content/ns1:ContentBody/ns1:MultiPart/ns1:BodyPart[2]/ns1:ContentBody"/>
                        </copy>                
                    </assign>
                    <invoke name="InvokeNotificationService"
                            portType="ns1:NotificationService"
                            partnerLink="NotificationService1"
                            inputVariable="varNotificationReq"
                            outputVariable="varNotificationResponse"
                            operation="sendEmailNotification"/>
                </sequence>
            </scope>
            <!--
              Asynchronous callback to the requester. (Note: the callback location and correlation id is transparently handled using WS-addressing.)
            -->
            <invoke name="callbackClient"
                    partnerLink="sendingemailwithattachmentsprcs_client"
                    portType="client:SendingEmailWithAttachmentsPrcsCallback"
                    operation="processResponse" inputVariable="outputVariable"/>
        </sequence>
    </process>
    I am able to generate Email with attachment but i cant see the data in the attached file.
    I think i need to convert the data before sending as a attachment. Could someone please help me in generating the txt files.
    Regards,
    Rajireddy.

    Re: sending fax

  • Send SOAP DIME Attachment (please comment on my sample code)

    Hi All,
    I had hard time trying to find a send SOAP DIME attachment
    code for the web service. And here it is, I wrote one,
    but I use to easy way to deploy the service.
    I just simply change the extension .java to .jws,
    so, can you all tell me whether it will be a problem or not ?
    And please review my code below, I debugged and no error,
    but I am not sure if it is working right.
    Basiclly 2 operations:
    public String generateID(int artID)
    public File detachFile(String filename)
    Please comment on this code, I am trying to make it
    more robust, so, that I can redo it and post it to share with
    everybody.
    thanks,
    Derek
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Iterator;
    import java.io.*;
    import java.security.*;
    import java.security.NoSuchAlgorithmException;
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.xml.soap.AttachmentPart;
    import org.apache.axis.AxisFault;
    import org.apache.axis.Message;
    import org.apache.axis.MessageContext;
    import org.apache.axis.attachments.Attachments;
    import org.apache.axis.attachments.AttachmentsImpl;
    import org.apache.log4j.Logger;
    public class AttachmentYPMG
         private static final Logger _logger = Logger.getLogger(AttachmentYPMG.class);
         public AttachmentYPMG()
         public String generateID(int artID)
              String artid = Integer.toString(artID);
              String md5_hash_string = plainStringToMD5(artid);
              return md5_hash_string;
         private String plainStringToMD5(String input) {
                // Some stuff we will use later
                MessageDigest md = null;
                byte[] byteHash = null;
                StringBuffer resultString = new StringBuffer();
                // Bad things can happen here
                try {
                  // Choose between MD5 and SHA1
                       md = MessageDigest.getInstance("MD5");
                } catch(NoSuchAlgorithmException e) {
                    System.out.println("NoSuchAlgorithmException caught!");
                    System.exit( -1);
                // Reset is always good
                md.reset();
                // We really need some conversion here
               md.update(input.getBytes());
                // There goes the hash
                byteHash = md.digest();
               //  Now here comes the best part
                for(int i = 0; i < byteHash.length; i++) {
                  resultString.append(Integer.toHexString(0xFF & byteHash));
              // That's it!
              return(resultString.toString());
         public File detachFile(String filename)
              InputStream is = null;
              FileOutputStream os = null;
              File file = null;
              int totalAttachments ;
              try
                   //Get all the attachments
                   AttachmentPart[] attachments = getMessageAttachments();
                   * getMessageAttachments() as provided by Steve Loughran in his mail
                   * to axis-user group
                   * http://www.mail-archive.com/[email protected]/msg08732.html
                   //Put the logic in a loop for totalAttachments for multiple
                   // attachments.
                   totalAttachments = attachments.length;
                   _logger.debug("saveFile(String filename = " + filename + ") - " +
                                  "Total Attachments Received Are: "+ totalAttachments);
                   //Extract the first attachment. (Since in this case we have only one attachment sent)
                   DataHandler dh = attachments[0].getDataHandler();
                   //Extract the file name of the first attachment.
                   String name = filename;
                   _logger.debug("saveFile(String filename = " + filename + ") - File received on server is: " + name);
                   //Get the streams to file and from attachment, then stream to disk
                   is = dh.getInputStream();
                   file = new File(name);
                   os = new FileOutputStream(file);
                   this.writeBuffersAndClose(is, os);
              } catch (Exception e)
                   _logger.error("detachFile(String filename = " + filename + ")", e);
                   //throw new AttachmentException(e);
              //if(file!= null)
                        return file;
              //else
                   //throw new AttachmentException("The attachment was not saved");
         * extract attachments from the current request
         * @return a list of attachmentparts or an empty array for no attachments
         * support in this axis buid/runtime
         private AttachmentPart[] getMessageAttachments() throws AxisFault
              * Reusing the method implementation for AttachmentPart[]
              * getMessageAttachments() as provided by Steve Loughran in his mail to
              * axis-user group
              * http://www.mail-archive.com/[email protected]/msg08732.html
              MessageContext msgContext = MessageContext.getCurrentContext();
              Message reqMsg = msgContext.getRequestMessage();
              Attachments messageAttachments = reqMsg.getAttachmentsImpl();
              if (null == messageAttachments)
                   System.out.println("no attachment support");
                   return new AttachmentPart[0];
              int attachmentCount = messageAttachments.getAttachmentCount();
              AttachmentPart attachments[] = new AttachmentPart[attachmentCount];
              Iterator it = messageAttachments.getAttachments().iterator();
              int count = 0;
              while (it.hasNext())
                   AttachmentPart part = (AttachmentPart) it.next();
                   attachments[count++] = part;
              return attachments;
         * Simple method for writing one stream from another.
         * @param is
         * @param os
         * @throws IOException
         private void writeBuffersAndClose(InputStream is, OutputStream os)
              throws IOException
              int i = 0;
              byte [] buffer = new byte[1024];
              while (i != -1)
                   i = is.read(buffer, 0, buffer.length);
                   if(i > 0)
                        os.write(buffer, 0, buffer.length);
              is.close();
              os.close();

    Hi All,
    I had hard time trying to find a send SOAP DIME attachment
    code for the web service. And here it is, I wrote one,
    but I use to easy way to deploy the service.
    I just simply change the extension .java to .jws,
    so, can you all tell me whether it will be a problem or not ?
    And please review my code below, I debugged and no error,
    but I am not sure if it is working right.
    Basiclly 2 operations:
    public String generateID(int artID)
    public File detachFile(String filename)
    Please comment on this code, I am trying to make it
    more robust, so, that I can redo it and post it to share with
    everybody.
    thanks,
    Derek
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.Iterator;
    import java.io.*;
    import java.security.*;
    import java.security.NoSuchAlgorithmException;
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.xml.soap.AttachmentPart;
    import org.apache.axis.AxisFault;
    import org.apache.axis.Message;
    import org.apache.axis.MessageContext;
    import org.apache.axis.attachments.Attachments;
    import org.apache.axis.attachments.AttachmentsImpl;
    import org.apache.log4j.Logger;
    public class AttachmentYPMG
         private static final Logger _logger = Logger.getLogger(AttachmentYPMG.class);
         public AttachmentYPMG()
         public String generateID(int artID)
              String artid = Integer.toString(artID);
              String md5_hash_string = plainStringToMD5(artid);
              return md5_hash_string;
         private String plainStringToMD5(String input) {
                // Some stuff we will use later
                MessageDigest md = null;
                byte[] byteHash = null;
                StringBuffer resultString = new StringBuffer();
                // Bad things can happen here
                try {
                  // Choose between MD5 and SHA1
                       md = MessageDigest.getInstance("MD5");
                } catch(NoSuchAlgorithmException e) {
                    System.out.println("NoSuchAlgorithmException caught!");
                    System.exit( -1);
                // Reset is always good
                md.reset();
                // We really need some conversion here
               md.update(input.getBytes());
                // There goes the hash
                byteHash = md.digest();
               //  Now here comes the best part
                for(int i = 0; i < byteHash.length; i++) {
                  resultString.append(Integer.toHexString(0xFF & byteHash));
              // That's it!
              return(resultString.toString());
         public File detachFile(String filename)
              InputStream is = null;
              FileOutputStream os = null;
              File file = null;
              int totalAttachments ;
              try
                   //Get all the attachments
                   AttachmentPart[] attachments = getMessageAttachments();
                   * getMessageAttachments() as provided by Steve Loughran in his mail
                   * to axis-user group
                   * http://www.mail-archive.com/[email protected]/msg08732.html
                   //Put the logic in a loop for totalAttachments for multiple
                   // attachments.
                   totalAttachments = attachments.length;
                   _logger.debug("saveFile(String filename = " + filename + ") - " +
                                  "Total Attachments Received Are: "+ totalAttachments);
                   //Extract the first attachment. (Since in this case we have only one attachment sent)
                   DataHandler dh = attachments[0].getDataHandler();
                   //Extract the file name of the first attachment.
                   String name = filename;
                   _logger.debug("saveFile(String filename = " + filename + ") - File received on server is: " + name);
                   //Get the streams to file and from attachment, then stream to disk
                   is = dh.getInputStream();
                   file = new File(name);
                   os = new FileOutputStream(file);
                   this.writeBuffersAndClose(is, os);
              } catch (Exception e)
                   _logger.error("detachFile(String filename = " + filename + ")", e);
                   //throw new AttachmentException(e);
              //if(file!= null)
                        return file;
              //else
                   //throw new AttachmentException("The attachment was not saved");
         * extract attachments from the current request
         * @return a list of attachmentparts or an empty array for no attachments
         * support in this axis buid/runtime
         private AttachmentPart[] getMessageAttachments() throws AxisFault
              * Reusing the method implementation for AttachmentPart[]
              * getMessageAttachments() as provided by Steve Loughran in his mail to
              * axis-user group
              * http://www.mail-archive.com/[email protected]/msg08732.html
              MessageContext msgContext = MessageContext.getCurrentContext();
              Message reqMsg = msgContext.getRequestMessage();
              Attachments messageAttachments = reqMsg.getAttachmentsImpl();
              if (null == messageAttachments)
                   System.out.println("no attachment support");
                   return new AttachmentPart[0];
              int attachmentCount = messageAttachments.getAttachmentCount();
              AttachmentPart attachments[] = new AttachmentPart[attachmentCount];
              Iterator it = messageAttachments.getAttachments().iterator();
              int count = 0;
              while (it.hasNext())
                   AttachmentPart part = (AttachmentPart) it.next();
                   attachments[count++] = part;
              return attachments;
         * Simple method for writing one stream from another.
         * @param is
         * @param os
         * @throws IOException
         private void writeBuffersAndClose(InputStream is, OutputStream os)
              throws IOException
              int i = 0;
              byte [] buffer = new byte[1024];
              while (i != -1)
                   i = is.read(buffer, 0, buffer.length);
                   if(i > 0)
                        os.write(buffer, 0, buffer.length);
              is.close();
              os.close();

  • Send file as attachment via mail

    Dear All,
    I want to send a report (ALV) as attachment to some mail. I am using SO_NEW_DOCUMENT_SEND_API1. Can you please suggest how can I send mail as attachment. I am able to send ALV report as HTML format. I want to send it as attachment.
    Thanks and regards,
    Atanu

    Hi,
    plz check the below code.
    it sends Excel sheet attachment with the mail using FM 'SO_DOCUMENT_SEND_API1'
    code>>>>>>>>>>>>>>>>>>>>.
    form send_email_with_attachment .
    DATA: l_t_objbin LIKE solisti1 OCCURS 100 WITH HEADER LINE.
      DATA: i_body TYPE soli_tab WITH HEADER LINE.
      DATA: l_t_objtxt  LIKE solisti1   OCCURS 100 WITH HEADER LINE.
      DATA: l_t_objpack LIKE sopcklsti1 OCCURS 2 WITH HEADER LINE.
      DATA: l_t_objhead LIKE solisti1   OCCURS 1 WITH HEADER LINE.
      DATA: l_t_reclist LIKE somlreci1  OCCURS 5 WITH HEADER LINE.
      DATA: w_tabln TYPE i .              "for number of table lines
      DATA: w_line        TYPE so_text255.       " Line of text
      DATA: l_doc_chng  LIKE sodocchgi1.
      DATA: l_tab_lines LIKE sy-tabix.
      DATA: l_att_lines TYPE i.
      DATA: lv_lines  TYPE i.
      DATA : BEGIN OF wa_mrpnm,
               werks TYPE ZCSVT024D-werks,
               dispo TYPE ZCSVT024D-dispo,
               name_first TYPE ZCSVT024D-name_first,
               name_last  TYPE ZCSVT024D-name_last,
             END OF wa_mrpnm,
             l_i_mrpnm LIKE STANDARD TABLE OF wa_mrpnm.
      DATA : l_name TYPE string.
    *Used for delimiting the columns in Excel Sheet.
      CLASS cl_abap_char_utilities DEFINITION LOAD.
      CONSTANTS:
      cr_mark(2) TYPE c VALUE cl_abap_char_utilities=>horizontal_tab.
      constants c_l_newline type ABAP_CHAR1 value %_NEWLINE. "#EC NOTEXT
      CLEAR : l_t_objpack,
      l_t_objhead,
      l_t_objbin,
      l_t_objtxt,
      l_t_reclist.
      REFRESH: l_t_objpack,
      l_t_objhead,
      l_t_objbin,
      l_t_objtxt,
      l_t_reclist.
    Creating the content of the e-mail message text
      IF sy-sysid(1) = 'P'.
        IF p_order = 'X'.
         l_doc_chng-obj_name   = 'Subcontracting Setup Report'(m02).
          CONCATENATE 'Details of Orders Extract'(028) 'for Plant'(029)
                       p_werks
                       INTO l_doc_chng-obj_descr SEPARATED BY space.
          l_doc_chng-doc_size = ( l_tab_lines - 1 ) * 255 + STRLEN( l_t_objtxt ).
        ELSE.
         l_doc_chng-obj_name   = 'TEST ONLY!! SC Setup Report'(m03).
          CONCATENATE 'Details of Forecast Extract'(030) 'for Plant'(029)
                       p_werks
                       INTO l_doc_chng-obj_descr SEPARATED BY space.
          l_doc_chng-doc_size = ( l_tab_lines - 1 ) * 255 + STRLEN( l_t_objtxt ).
        ENDIF.
      ELSE.
        IF p_order = 'X'.
         l_doc_chng-obj_name   = 'Subcontracting Setup Report'(m02).
          CONCATENATE 'Details of Orders Extract'(028) 'for Plant'(029)
                       p_werks 'TEST TEST TEST'
                       INTO l_doc_chng-obj_descr SEPARATED BY space.
          l_doc_chng-doc_size = ( l_tab_lines - 1 ) * 255 + STRLEN( l_t_objtxt ).
        ELSE.
         l_doc_chng-obj_name   = 'TEST ONLY!! SC Setup Report'(m03).
          CONCATENATE 'Details of Forecast Extract'(030) 'for Plant'(029)
                       p_werks 'TEST TEST TEST'
                       INTO l_doc_chng-obj_descr SEPARATED BY space.
          l_doc_chng-doc_size = ( l_tab_lines - 1 ) * 255 + STRLEN( l_t_objtxt ).
        ENDIF.
      ENDIF.
      l_t_objtxt = 'Hi,'(036).
      APPEND l_t_objtxt.
      CLEAR l_t_objtxt.
      APPEND l_t_objtxt.
      CONCATENATE 'Please open the attachment to review details of the Report'(031)
                  'for plant'(029) p_werks INTO l_t_objtxt
                   SEPARATED BY space.
      APPEND l_t_objtxt.
      CLEAR l_t_objtxt.
      APPEND l_t_objtxt.
      DESCRIBE TABLE t_ddow LINES sy-tfill .
      IF sy-tfill GT 0 .
        MOVE 'These Materials have been marked as DDOW materials.'(032)
                TO l_t_objtxt.
        APPEND l_t_objtxt.
        CLEAR l_t_objtxt.
        APPEND l_t_objtxt.
        APPEND l_t_objtxt.
        APPEND l_t_objtxt.
        CONCATENATE 'Note! - This is an automatically generated email by the'(034)
                         'SAP system. Pls do not reply to the sender.'(035)
                   INTO  l_t_objtxt
                   SEPARATED BY space.
        APPEND l_t_objtxt.
        DESCRIBE TABLE l_t_objtxt LINES l_tab_lines.
        READ TABLE l_t_objtxt INDEX l_tab_lines.
       l_doc_chng-doc_size = ( l_tab_lines - 1 ) * 255 + STRLEN( l_t_objtxt )
      Creating the entry for the email text in the packing list
        CLEAR l_t_objpack-transf_bin.
        l_t_objpack-head_start = 1.
        l_t_objpack-head_num = 1.
        l_t_objpack-body_start = 1.
        l_t_objpack-body_num = l_tab_lines.
        l_t_objpack-doc_type = 'RAW'.
        lv_lines = l_tab_lines.
        APPEND l_t_objpack.
    Columns Heading for Excel Attachment.
        CONCATENATE  'MRP Controller'(044)
                     'MRP Name'(047)
                     'Material'(037)
                     'Plant'(026)
                     'PP Cal'(038)
                     'Ship Date'(009)
                     'PO Number'(014)
                     'PO Line'(033)
                     'PP Text'(041)
             INTO i_body
            SEPARATED BY cr_mark.
        concatenate ' ' i_body into i_body separated by c_l_newline.
        APPEND i_body TO l_t_objtxt.
        CLEAR i_body.
      Get MRP Names
        SELECT werks dispo name_first name_last
          FROM ZCSVT024D
          INTO TABLE l_i_mrpnm
          FOR ALL ENTRIES IN t_ddow
          WHERE werks = t_ddow-werks
            AND dispo = t_ddow-dispo.
        IF sy-subrc = 0.
          SORT l_i_mrpnm by werks dispo.
        ENDIF.
    Data to be shown in Excel Sheet.
        LOOP AT t_ddow INTO w_ddow.
          CLEAR : l_name.
          READ TABLE l_i_mrpnm INTO wa_mrpnm WITH KEY werks = w_ddow-werks
                                                      dispo = w_ddow-dispo
                                                      BINARY SEARCH.
          IF sy-subrc = 0.
            CONCATENATE wa_mrpnm-name_first wa_mrpnm-name_last
              INTO l_name SEPARATED BY space.
          ENDIF.
          CONCATENATE  w_ddow-dispo
                       l_name
                       w_ddow-matnr
                       w_ddow-werks
                       w_ddow-mrppp
                       w_ddow-datum
                       w_ddow-ebeln
                       w_ddow-ebelp
                       w_ddow-pptxt
                INTO i_body
            SEPARATED BY cr_mark.
          concatenate ' ' i_body into i_body separated by c_l_newline.
          APPEND i_body TO l_t_objtxt.
          CLEAR : w_ddow.
        ENDLOOP.
        DESCRIBE TABLE l_t_objtxt LINES l_tab_lines.
        DESCRIBE TABLE l_t_objtxt LINES l_att_lines.
        l_tab_lines = l_tab_lines - lv_lines.
      Creating the entry for attachment in the packing list
      objpack-transf_bin = 'X'.
        lv_lines = lv_lines + 1.
        l_t_objpack-head_start = 2.
        l_t_objpack-head_num = 1.
        l_t_objpack-body_start = lv_lines.
        l_t_objpack-body_num = l_tab_lines.
        l_t_objpack-doc_type = 'XLS'.
        l_t_objpack-obj_name = 'DDOW_Materials'(045).
        l_t_objpack-obj_descr = 'DDOW Marked Materials'(046).
        l_t_objpack-doc_size = l_tab_lines * 255.
        APPEND l_t_objpack.
        lv_lines = l_att_lines.
         **RECEIVERS...
        LOOP AT t_ddow INTO w_ddow.
          REFRESH l_t_reclist .
          CLEAR l_t_reclist.
    * get the MRP controller from table
          READ TABLE t_mrpc INTO w_mrpc WITH KEY werks = p_werks
                                                 dispo = w_ddow-dispo
                                                 BINARY SEARCH .
          IF sy-subrc EQ 0 .
            MOVE: 'X'               TO l_t_reclist-express   ,
                  'U'               TO l_t_reclist-rec_type  ,
                  w_mrpc-smtp_addr  TO l_t_reclist-receiver  .
                  APPEND l_t_reclist.
            EXIT.
          ENDIF.
        ENDLOOP.
      Sending the document
        IF NOT l_t_reclist[] IS INITIAL.
          CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
            EXPORTING
              document_data              = l_doc_chng
              commit_work                = 'X'
            TABLES
              packing_list               = l_t_objpack
              object_header              = l_t_objhead
              contents_bin               = l_t_objbin
              contents_txt               = l_t_objtxt
              receivers                  = l_t_reclist
            EXCEPTIONS
              too_many_receivers         = 1
              document_not_sent          = 2
              operation_no_authorization = 4
              OTHERS                     = 99.
        ENDIF.
        IF sy-subrc <> 0.
    * Do nothing
        ELSE.
          COMMIT WORK AND WAIT.
          MESSAGE s899(8a) WITH 'Email Message sent successfully'."#EC
        ENDIF.
      ENDIF.
    <<<<<<<<<<<<<<<<<<<<<<<
    regards,
    vikas.
    plz reward if helpful..

Maybe you are looking for