Send Emails with Attachments of any Format
Skip to end of metadata
Created by V S BHARGAV MYLAVARAPU, last modified by Former Member on Oct 24, 2013
Go to start of metadata
Hi All,
Happy SDN..!
Recently I got a chance to do some R&D in sending emails using ABAP. I searched all the SCN and other Technical forums to find a easy solution to perform this operation. But unsucessfull :( . We have several options given by SAP to send mails to several people with attachments. Everyone knows how to perform this operation. The new thing here which I want to explain to all via Wiki SDN is Sending those mails in a bulk format. For Example, I have kept 100 documents in a Folder on my desktop. The folder contains different types of documents like, PDF, EXCEL, WORD, JPEG, Etc... Now I need to send all those documents one by one via Email to a specific Mail ID with attachments. Since the folder can contain any type of document, The below program will solve this kind of requirement. Please find the below screen shots of the program for a easy go-thru of what exactly this program does. Now a Email will be generated to the given Mail ID as shown in the below screen shots. Similarly you will get different mails with each attachment in a seperate mail.
The explaination of the program is as follows.
Error rendering macro 'code': Invalid value specified for parameter 'com.atlassian.confluence.ext.code.render.InvalidValueException'
REPORT YSEND_BULK_DOCUMENTS_FROM_A_FOLDER.
PARAMETERS : P_ATTACH TYPE CHAR200 OBLIGATORY, " Select the Folder on the Desktop from F4 help
P_EMAIL TYPE CHAR50 OBLIGATORY, " Email ID
P_SUBJ TYPE CHAR50 OBLIGATORY. " Subject of the Email
DATA : T_HEXTAB TYPE TABLE OF STRING,
L_FILE TYPE STRING,
T_MAILHEX TYPE SOLIX_TAB,
LV_COUNT TYPE I,
GV_EMAIL TYPE ADR6-SMTP_ADDR,
T_BODY TYPE TABLE OF SOLISTI1,
GR_RECIPIENT TYPE REF TO IF_RECIPIENT_BCS,
TL_TEXTPOOL TYPE TABLE OF TEXTPOOL,
WA_TEXTPOOL LIKE LINE OF TL_TEXTPOOL,
IT_CONTENTS TYPE SOLI_TAB,
LV_ATTACH_NAME TYPE SOOD-OBJDES,
L_SUBJECT TYPE SO_OBJ_DES,
L_DOCUMENT TYPE REF TO CL_DOCUMENT_BCS,
W_DOCUMENT TYPE REF TO CL_BCS,
WA_CONTENTS LIKE LINE OF IT_CONTENTS,
LV_FILENAME TYPE STRING,
L_RESULT TYPE OS_BOOLEAN,
LV_STRING TYPE STRING.
DATA : FILE_TABLE LIKE TABLE OF SDOKPATH WITH HEADER LINE .
DATA : DIR_TABLE LIKE TABLE OF SDOKPATH WITH HEADER LINE .
DATA : FILE_COUNT TYPE I ,
DIRCOUNT TYPE I .
AT SELECTION-SCREEN ON VALUE-REQUEST FOR P_ATTACH.
CALL METHOD CL_GUI_FRONTEND_SERVICES=>DIRECTORY_BROWSE
CHANGING
SELECTED_FOLDER = LV_STRING
EXCEPTIONS
CNTL_ERROR = 1
ERROR_NO_GUI = 2
NOT_SUPPORTED_BY_GUI = 3
OTHERS = 4.
IF SY-SUBRC <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ELSE.
P_ATTACH = LV_STRING.
ENDIF.
START-OF-SELECTION.
* CHECK IF THE FOLDER PATH IS INITIAL, IF INITIAL LEAVE THE PROGRAM, ELSE COPY THE SUBJECT. ---> IT ALL DEPENDS ON HOW YOU VALIDATE.
IF P_ATTACH IS INITIAL.
LEAVE LIST-PROCESSING.
ELSE.
L_SUBJECT = P_SUBJ.
ENDIF.
* GETS ALL THE FILES NAMES IN THE SELECTED FOLDER
CALL FUNCTION 'TMP_GUI_DIRECTORY_LIST_FILES'
EXPORTING
DIRECTORY = P_ATTACH
IMPORTING
FILE_COUNT = FILE_COUNT
DIR_COUNT = DIRCOUNT
TABLES
FILE_TABLE = FILE_TABLE
DIR_TABLE = DIR_TABLE
EXCEPTIONS
CNTL_ERROR = 1
OTHERS = 2.
* TELL HOW MANY FIELDS EXISTS
WRITE:/ 'no of files in the floder is : '(005), FILE_COUNT.
SKIP 1.
WRITE:/ SY-ULINE.
WRITE:/ SY-ULINE.
* PROCESS THE DATA TO SEND MAIL WITH ATTACHMENT.
LOOP AT FILE_TABLE.
LV_COUNT = SY-TABIX.
CONCATENATE P_ATTACH '\' FILE_TABLE INTO LV_FILENAME.
MOVE LV_FILENAME TO L_FILE.
CALL FUNCTION 'GUI_UPLOAD'
EXPORTING
FILENAME = L_FILE
FILETYPE = 'BIN'
TABLES
DATA_TAB = T_MAILHEX
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.
IF SY-SUBRC <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
* YOU NEED TO MAINTAIN TEXT SYMBOLS AND WANT TO READ THEM IN THE PROGRAM
READ TEXTPOOL SY-REPID INTO TL_TEXTPOOL LANGUAGE SY-LANGU.
* MY TEXT SYMBOL IS " T04: You can Add your Body here"
READ TABLE TL_TEXTPOOL INTO WA_TEXTPOOL WITH KEY ID = 'I'
KEY = 'T04' BINARY SEARCH.
IF SY-SUBRC = 0.
WA_CONTENTS-LINE = WA_TEXTPOOL-ENTRY.
APPEND WA_CONTENTS TO IT_CONTENTS.
ENDIF.
* CREATE THE DOCUMENT WITH CONTENTS
CREATE OBJECT L_DOCUMENT.
L_DOCUMENT = CL_DOCUMENT_BCS=>CREATE_DOCUMENT(
I_TYPE = 'HTM'
I_SUBJECT = L_SUBJECT
I_LENGTH = '1000'
I_LANGUAGE = SY-LANGU
I_IMPORTANCE = '1'
I_TEXT = IT_CONTENTS ).
* ATTACH THE FILE, THE ATTACHMENT TYPE SHOULD BE BIN TO ACCEPT ANY KIND OF ATTACHMENT, INCLUDING VIDEOS, AUDIO FILES ETC...
LV_ATTACH_NAME = FILE_TABLE.
CALL METHOD L_DOCUMENT->ADD_ATTACHMENT
EXPORTING
I_ATTACHMENT_TYPE = 'BIN'
I_ATTACHMENT_SUBJECT = LV_ATTACH_NAME
I_ATT_CONTENT_HEX = T_MAILHEX.
* CREATING PERSISTENT OBJECT WILL ALLOW YOU TO SET THE DOCUMENT IN THE MAIL
W_DOCUMENT = CL_BCS=>CREATE_PERSISTENT( ).
CALL METHOD W_DOCUMENT->SET_DOCUMENT( L_DOCUMENT ).
* EMAIL AS GIVEN IN THE SELECTION SCREEN.
GV_EMAIL = P_EMAIL.
GR_RECIPIENT = CL_CAM_ADDRESS_BCS=>CREATE_INTERNET_ADDRESS( GV_EMAIL ).
"Add recipient to send request
CALL METHOD W_DOCUMENT->ADD_RECIPIENT
EXPORTING
I_RECIPIENT = GR_RECIPIENT
I_EXPRESS = 'X'.
* SEND THE MAIL
CALL METHOD W_DOCUMENT->SEND(
EXPORTING
I_WITH_ERROR_SCREEN = 'X'
RECEIVING
RESULT = L_RESULT ).
* YOU CAN VERIFY THE STATUS IN THE LIST, YOU CAN ALSO SUBMIT THIS AS A BACKGROUND JOB.
IF L_RESULT = 'X'.
WRITE :/ , 1(9) LV_COUNT, 10(55) FILE_TABLE-PATHNAME.
WRITE : 56(1) '-', 58(20) 'Mail sent'(003).
COMMIT WORK.
ELSE.
WRITE :/ , 1(9) LV_COUNT, 10(55) FILE_TABLE-PATHNAME.
WRITE : 56(1) '-', 58(30) 'Error in sending Mail'(004).
ROLLBACK WORK.
ENDIF.
REFRESH IT_CONTENTS[].
ENDLOOP.
You can Verify the Status of the Mail in SOST and SCOT as shown below respectively. I Hope this WIKI would help many SAPians in sending mails with any type of attachment using ABAP. Thanks & Regards, Venkat Sesha
emails
sost
scot
attachments
attachment
formats
3 Comments
Former Member
Hi Venkat Sesha,
Thank you for the detailed explanation with screen shots. It is very helpful.
We tried using this and it worked perfectly. But , we had an issue with the sender email . By default this program is taking the SAP logon as the email id.
Is there a way we can specify the sender email id?
Thanks
Sujata Kolla
Aug 06, 2014
Former Member
Hi Venkat,
I really appreciate your effort. Wonder full..Keep it up..
Regards,
Abu Fazi
Feb 04, 2015
V S BHARGAV MYLAVARAPU
Thanks for your complements...
Working with files
Skip to end of metadata
Created by Sandra Rossi, last modified on Nov 04, 2009
Go to start of metadata
Table of contents
Introduction
Working with files on the application server
How to create or write to a file
How to read a file
Checking file existence
How to get list of files in a directory
Is there a search help for selecting a file
Best practice
Miscellaneous
Working with files on presentation server
How to create or write a file
How to read a file
Checking file existence
How to get list of files in a directory
Is there a search help for selecting a file or directory
Is it possible to work in background?
Miscellaneous
Copying from server to frontend or vice versa
File compression (zip)
Working with special files
Excel file types
OLE/DOI for Office native files (Excel, Word, etc.)
Introduction
In this article, only general directions are given. You may find snippets here
Files are handled differently when they are on the application server, or on the presentation server
Files may be processed in 2 modes, either text (in a given encoding), or binary (generated by a software like Microsoft Office, Adobe Acrobat, etc.) From ABAP, you may directly write and read text files, while binary files can only be written and read by the software. The mode is chosen when opening the file.
Working with files on the application server
Transaction code AL11 takes you to the application server in which you find the sap directories and the files inside the directories. The configure button on the main screen can be used to create and manage links to existing directories.
Files may be processed in 2 ways, decided in OPEN DATASET statement: either as text files with a given encoding (IN TEXT MODE, ENCODING and CODE PAGE additions), or as binary files (IN BINARY MODE addition).
How to create or write to a file
Use ABAP statements OPEN DATASET with FOR OUTPUT keyword, TRANSFER, CLOSE DATASET.
How to read a file
Use ABAP statements OPEN DATASET with FOR INPUT keyword, READ DATASET and CLOSE DATASET.
Checking file existence
either OCS_GET_FILE_INFO function module
or "OPEN DATASET" ABAP statement
How to get list of files in a directory
To read the names of files present in a particular path on the application server we may use SUBST_GET_FILE_LIST or EPS_GET_DIRECTORY_LISTING function modules.
Is there a search help for selecting a file
F4_DXFILENAME_TOPRECURSION function module may be used to display a search help to choose a file
Snippet
Best practice
Instead of hardcoding the file names, it is possible to define generic names which are called "logical filenames". They may be defined using FILE transaction code, and used using FILE_GET_NAME function module.
Miscellaneous
sdn contribution : ABAP Server Side File Access, by Thomas Jung (class ZCL_ES_SERVER_FILE_ACCESS)
Note 752859: sapiconv - a tool for converting the encoding of files
Working with files on presentation server
How to create or write a file
either GUI_DOWNLOAD function module Snippet
or CL_GUI_FRONTEND_SERVICES=>GUI_DOWNLOAD method Snippet
Note: DOWNLOAD and WS_DOWNLOAD function modules are obsolete
How to read a file
either GUI_UPLOAD function module Snippet
or CL_GUI_FRONTEND_SERVICES=>GUI_UPLOAD method
Note: UPLOAD and WS_UPLOAD function modules are obsolete
Checking file existence
either DX_FILE_EXISTENCE_CHECK function module
or CL_GUI_FRONTEND_SERVICES=>FILE_EXIST method
How to get list of files in a directory
either TMP_GUI_DIRECTORY_LIST_FILES function module
or CL_GUI_FRONTEND_SERVICES=>DIRECTORY_LIST_FILES method
Is there a search help for selecting a file or directory
For selecting a *file", you may use:
CL_GUI_FRONTEND_SERVICES=>FILE_OPEN_DIALOG method (Basis, 4.6 and after): displays list as a popup with title "Open", and returns the name of selected file
CL_GUI_FRONTEND_SERVICES=>FILE_SAVE_DIALOG method (Basis, 4.6 and after): displays list as a popup with title "Save", and returns the name of selected file Snippet
WS_FILENAME_GET function module (Basis, any release)
F4_FILENAME function module (R/3 and ECC only)
For selecting a directory, you may use:
CL_GUI_FRONTEND_SERVICES=>DIRECTORY_BROWSE method
Is it possible to work in background?
No, this functionality is not supplied because presentation servers may be switched off at any time without guarantee (see Note 7925 - Graphics, Upload, Download do not work in backgrnd). Workarounds may be:
Work with files on application server. The user may copy files from or to the application server when he is connected
If you take decisions to make the presentation server work as a server (always the same computer, and it would be switched on), consider it is an RFC server: see SDN article Communication to Presentation Server in Background Mode for more information.
Miscellaneous
CL_GUI_FRONTEND_SERVICES class provides many other methods about files
Copying from server to frontend or vice versa
CL_GUI_FRONTEND_SERVICES=>FILE_COPY method
SAP commander
R/3 and ECC: transaction codes CG3Y (from server to frontend) and CG3Z (from frontend to server)
File compression (zip)
Class CL_ABAP_ZIP may be used to read or write a zipped file.
On the application server, OPEN DATASET statement may be used with FILTER addition to compress or uncompress
Note: there is also class CL_ABAP_GZIP, but it can't be used to process files, it may just be used to compress or uncompress data in memory.
Working with special files
Excel file types
See Excel file types (CSV, XML, XSLX, OLE)
OLE/DOI for Office native files (Excel, Word, etc.)
When a user is connected to SAP via SAPGUI for Windows, you may use OLE ABAP statements (see ABAP documentation), or Desktop Office Integration framework (it also uses OLE).
It is not possible to use OLE or DOI in a program disconnected from SAPGUI (background job for example).
It is possible to create Office documents using XML files
No labels
5 Comments
Saifur Rahaman
My SIP Project In Tata Steel worked out based on this concept..thnx a lot for keep us update about small but important things
Jan 01, 2010
Unknown User (szpe7do)
Do not use SUBST_GET_FILE_LIST! In BASIS 701, SAP changes the code to a single line:
raise access_error.
You won't get very far with that.
May 31, 2011
Custodio de Oliveira
To read a file from application server in one shot: CL_RSAN_UT_APPSERV_FILE_READER=>APPSERVER_FILE_READ
To write: CL_RSAN_UT_APPSERV_FILE_WRITER=>APPSERVER_FILE_WRITE
Nov 02, 2011
Former Member
This document and the code snippet section is very helpful. But the FM is given for F4 help for Application Server file is F4_DXFILENAME_4_DYNP . I tried use this FM but it is not working for my case. For this requirement /SAPDMC/LSM_F4_SERVER_FILE FM can be used.
Jan 30, 2015
Former Member
Issue with this article, please do NOT recommend using function module EPS_GET_DIRECTORY_LISTING. It is an SAP projects(not PS) function module which requires Projects authorizations which are related to configuration and NOT related to business processes.
Sending Email with excel attachment
Skip to end of metadata
Created by Saravanan Madhappan on Dec 02, 2013
Go to start of metadata
Author: Saravanan M
Submitted: <06 Sep 2011> Related Links:
Class CL_BCS: http://help.sap.com/saphelp_sm32/helpdata/en/2d/1c5d3aebba4c38e10000000a114084/content.htm
Class CL_DOCUMENT_BCS: http://help.sap.com/saphelp_NW70EHP1core/helpdata/en/8c/5bf13b68402b69e10000000a11402f/content.htm
Description
This article describes how to convert internal table value into excel and sending excel in email using class CL_BCS and CL_DOCUMENT_BCS.
Selection Screen:
Selection Screen.bmp
May 9, 2014 13 minute read
Sending Email with PDF Attachment
FollowRSS feedLike
8 Likes 35,602 Views 18 Comments
Hi All,This blog is with reference to one of the threads(question) in SCN (http://scn.sap.com/thread/3373098) wherein the requirement was to send email with PDF attachment.
As I have implemented the same for one similar requirement I replied to this question and wanted to share the steps/code if required.I have documented all the steps and code in a MS word document but as SCN does not allow to upload MS Word document ,I told to send one email to my personal email ID(mentioned in the reply) and I will send the MS word document.
Thereafter I kept on receiving a lot of email requests to share the word document.So thought of creating this blog with all those steps and code so that anyone needs those can get them here in SCN itself .And also they will not need to wait for my email reply instead they can get it immediately here in SCN itself.
I will maintain this blog link to that original thread/question.
Here are the steps and codes for the development of the class, method to send email with PDF attachment(content of internal table) and also one sample program to test the same.
Step1: Go to tcode SE24-> Provide the class name
Properties:
Step2 : Declare the PDF Method: SEND_PDF_FILE
PDF: Parameters:
Parameters list to copy and paste:
*———————————————————————————————————————————-*
IM_FILE_HEADER_TEXT Importing Type STRING Header Text
IM_EMAIL_SUBJECT_LINE Importing Type SO_OBJ_DES Subject Line
IM_EMAIL_BODY_TEXT Importing Type BCSY_TEXT Body Text
IM_EMAIL_ADDRESS Importing Type ZTP_SMTP_TAB Email Address
IM_EMAIL_DIST_NAME Importing Type SO_OBJ_NAM Email Distribution Name
IM_EMAIL_DIST_ID Importing Type SO_OBJ_ID Email Distribution Id
IM_ATTACHMENT_NAME Importing Type SOOD-OBJDES Attachment Name
IM_FILE_DELIMETER Importing Type C File Delimiter
IM_ITAB_1 Importing Type ZTP_TEXT_TAB Itab with data content
IM_ITAB_2 Importing Type SOLI_TAB Itab with column headers
EX_SEND_TO_ALL Exporting Type OS_BOOLEAN Send Email
IM_EMAIL_DO_NOT Importing Type CHAR1 Flag to determine whether mail needs to be sent or not
IM_LAYOUT Importing Type SYPAART Layout mode Portrait or Landscape
EX_PDF_TABLE Exporting Type RCL_BAG_TLINE Contains converted data in PDF format
*————————————————————————————————————————————————————-*
Custom types are highlighted , please find them below:
Step3 : Custom types needs to be created which is used above:
Email Table Type :
Corresponding structure:
Data Content table type:
Corresponding structure:
Exceptions:
Step4 : Paste the below code in the method body.
Sample code :
*———————————————————————————————————————————–*
Please find below the method code.
METHOD send_pdf_file.
*******************************************************************************
* S-H-O-R-T-----D-E-S-C-R-I-P-T-I-O-N *
*******************************************************************************
*Program Description : Method to send email with pdf attatchment. *
*Developer : Hafizul Mollah *
*Brief Description : This method is used to send email with *
* a pdf attachment. It can be used to send the email *
* to multiple email addresses(To, CC,BCC) or to a *
* distribution name or distribution id. *
*******************************************************************************
* CONSTANTS----------------------------------------------------------------*
CONSTANTS:
c_tab TYPE c VALUE cl_bcs_convert=>gc_tab,
c_crlf TYPE c VALUE cl_bcs_convert=>gc_crlf,
gc_tab TYPE c VALUE cl_bcs_convert=>gc_tab,
gc_crlf TYPE c VALUE cl_bcs_convert=>gc_crlf.
* TYPES----------------------------------------------------------------*
TYPES: BEGIN OF ty_itab,
line TYPE ztp_text_struct,
END OF ty_itab,
BEGIN OF ty_itab2,
line TYPE soli,
END OF ty_itab2,
BEGIN OF ty_header,
field TYPE char80,
END OF ty_header,
BEGIN OF ty_field,
field TYPE char40,
END OF ty_field,
BEGIN OF ty_maxlen,
maxlen TYPE i,
END OF ty_maxlen.
* INTERNAL TABLES------------------------------------------------------*
DATA:
li_dlientries TYPE STANDARD TABLE OF sodlienti1,
li_binary_content TYPE solix_tab,
li_main_text TYPE bcsy_text,
li_recipient TYPE ztp_smtp_tab,
i_header TYPE STANDARD TABLE OF ty_header,
i_maxlen TYPE STANDARD TABLE OF ty_maxlen,
li_final TYPE ztp_text_tab,
i_field TYPE STANDARD TABLE OF ty_field.
* STRUCTURES-----------------------------------------------------------*
DATA:
st_itab1 TYPE ty_itab,
st_itab2 TYPE ty_itab2,
st_email_addr TYPE ztp_smtp_struct,
st_dlientry TYPE sodlienti1,
st_body TYPE soli.
* FIELD-SYMBOLS----------------------------------------------------*
FIELD-SYMBOLS: <f_source> TYPE any,
<f_wa_filetab> TYPE any,
<l_xline> TYPE x,
<t_dyntable> TYPE STANDARD TABLE , "Dynamic internal table name
<fs_dyntable> TYPE any , "Field symbol to create work area
<fs_fldval> TYPE any, " Field symbol to assign value
<fs> TYPE any.
* VARIABLES------------------------------------------------------------*
DATA:
wa_header TYPE ty_header,
send_request TYPE REF TO cl_bcs,
document TYPE REF TO cl_document_bcs,
recipient TYPE REF TO if_recipient_bcs,
bcs_exception TYPE REF TO cx_bcs,
l_size TYPE so_obj_len,
l_sent_to_all TYPE os_boolean,
l_dliname TYPE so_obj_nam,
l_dlidata TYPE sodlidati1,
l_string TYPE string,
l_cl_name TYPE string,
l_mailcc TYPE c,
l_mailbcc TYPE c,
l_recipient TYPE ad_smtpadr,
t_newtable TYPE REF TO data,
t_newline TYPE REF TO data,
t_fldcat TYPE lvc_t_fcat,
wa_it_fldcat TYPE lvc_s_fcat,
wa_colno(2) TYPE n,
wa_flname TYPE string,
t_attachment TYPE solisti1 ,
pdf_content TYPE solix_tab,
lp_pdf_size TYPE so_obj_len,
main_text TYPE bcsy_text,
binary_content TYPE solix_tab,
size TYPE so_obj_len,
sent_to_all TYPE os_boolean,
lv_string TYPE string,
wa_tab1 TYPE ztp_text_struct,
wa_tab2 TYPE soli,
pdf_xstring TYPE xstring,
it_pdf_table TYPE rcl_bag_tline,
wa_pdfline LIKE LINE OF it_pdf_table,
l_column_index TYPE sy-index,
l_rc TYPE c,
l_handle TYPE sy-tabix,
l_spoolid TYPE tsp01-rqident,
l_str(255) TYPE c,
params TYPE pri_params,
valid TYPE char1,
l_pdf_bytecount TYPE i,
wa_im_itab_1 TYPE ztp_text_struct,
g_data TYPE char25,
l_output TYPE char40,
l_col_cnt TYPE i,
l_maxcnt TYPE i,
wa_field TYPE ty_field,
wa_maxlen TYPE ty_maxlen,
l_index TYPE char2,
lwa_final TYPE ztp_text_struct,
l_field TYPE string,
l_rec TYPE i,
wa_im_itab_2 TYPE soli,
wa_im_itab_3 TYPE soli,
l_field_conv TYPE string,
l_comp TYPE string,
l_pos TYPE i VALUE 1,
l_sp_id TYPE tsp01_sp0r-rqid_char.
l_field = ' '.
CONCATENATE im_file_header_text
gc_crlf gc_crlf
INTO lv_string.
SET LOCALE LANGUAGE 'E'."added
CALL FUNCTION 'GET_PRINT_PARAMETERS'
EXPORTING
destination = 'LOCL'
*LINE_SIZE = 100
immediately = ' '
no_dialog = 'X'
layout = im_layout
*LINE_COUNT = 500000
line_size = 200
IMPORTING
out_parameters = params
valid = valid.
SPLIT im_file_header_text AT '#' INTO TABLE i_header.
SET LOCALE LANGUAGE 'E'.
NEW-PAGE PRINT ON PARAMETERS params NO DIALOG NO-TITLE NO-HEADING.
LOOP AT i_header INTO wa_header.
WRITE : wa_header-field.
ENDLOOP.
LOOP AT im_itab_2 INTO wa_im_itab_2.
IF sy-tabix = 1.
l_field = wa_im_itab_2.
ELSE.
CONCATENATE l_field wa_im_itab_2 INTO l_field SEPARATED BY '|'.
ENDIF.
ENDLOOP.
APPEND l_field TO li_final.
LOOP AT im_itab_1 INTO wa_im_itab_1.
APPEND wa_im_itab_1 TO li_final.
ENDLOOP.
READ TABLE li_final INTO lwa_final INDEX 1. "reading the columns name
IF sy-subrc = 0.
SPLIT lwa_final AT '|' INTO TABLE i_field.
ENDIF.
DESCRIBE TABLE i_field LINES l_rec.
LOOP AT i_field INTO wa_field.
l_index = sy-tabix.
CONCATENATE 'COL' l_index INTO wa_flname.
wa_it_fldcat-fieldname = wa_flname.
wa_it_fldcat-outputlen = 40.
wa_it_fldcat-datatype = 'CHAR'.
APPEND wa_it_fldcat TO t_fldcat.
CLEAR wa_it_fldcat.
ENDLOOP.
* Create dynamic internal table and assign to FS
CALL METHOD cl_alv_table_create=>create_dynamic_table
EXPORTING
it_fieldcatalog = t_fldcat
IMPORTING
ep_table = t_newtable.
ASSIGN t_newtable->* TO <t_dyntable>.
REFRESH <t_dyntable>.
* Create dynamic work area and assign to FS
CREATE DATA t_newline LIKE LINE OF <t_dyntable>.
ASSIGN t_newline->* TO <fs_dyntable>.
CLEAR <fs_dyntable>.
*****************reading the data value********************************************
REFRESH i_field.
LOOP AT li_final INTO lwa_final.
SPLIT lwa_final AT '|' INTO TABLE i_field.
SET LOCALE LANGUAGE 'E'.
LOOP AT i_field INTO wa_field.
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_OUTPUT'
EXPORTING
input = wa_field-field
IMPORTING
output = l_output.
CONCATENATE l_field_conv l_output INTO l_field_conv RESPECTING BLANKS.
ENDLOOP.
<fs_dyntable> = l_field_conv.
APPEND <fs_dyntable> TO <t_dyntable>.
CLEAR:l_field_conv.
ENDLOOP.
DO l_rec TIMES.
REFRESH: i_field.
l_col_cnt = l_col_cnt + 1.
LOOP AT <t_dyntable> INTO <fs_dyntable>.
IF <fs> IS ASSIGNED.
UNASSIGN <fs>.
ENDIF.
DO.
ASSIGN COMPONENT l_col_cnt OF STRUCTURE <fs_dyntable> TO <fs>.
IF sy-subrc <> 0.
EXIT.
ENDIF.
wa_field-field = <fs>.
*condense wa_field-field.
APPEND wa_field TO i_field.
CLEAR: wa_field.
EXIT.
ENDDO.
ENDLOOP.
*****************calculating tha maximum length of domain values********************************************
LOOP AT i_field INTO wa_field.
l_maxcnt = strlen( wa_field-field ).
IF wa_maxlen-maxlen < l_maxcnt .
wa_maxlen-maxlen = l_maxcnt.
ENDIF.
CLEAR:l_maxcnt.
ENDLOOP.
APPEND wa_maxlen TO i_maxlen .
CLEAR: wa_maxlen,l_maxcnt.
ENDDO.
SKIP 2.
*****************writing the column names and data value********************************************
LOOP AT <t_dyntable> INTO <fs_dyntable>.
IF <fs> IS ASSIGNED.
UNASSIGN <fs>.
ENDIF.
DO.
ASSIGN COMPONENT sy-index OF STRUCTURE <fs_dyntable> TO <fs>.
IF sy-subrc <> 0.
EXIT.
ENDIF.
l_comp = <fs>.
IF sy-index = 1.
WRITE:/ l_comp.
ELSE.
l_rec = sy-index - 1.
READ TABLE i_maxlen INTO wa_maxlen INDEX l_rec.
IF sy-subrc = 0.
l_pos = l_pos + wa_maxlen-maxlen + 1.
WRITE AT l_pos l_comp.
ENDIF.
ENDIF.
CLEAR:l_rec,l_comp.
ENDDO.
l_pos = 1.
ENDLOOP.
NEW-PAGE PRINT OFF.
l_spoolid = sy-spono.
SET LOCALE LANGUAGE 'E'.
CALL FUNCTION 'CONVERT_ABAPSPOOLJOB_2_PDF'
EXPORTING
src_spoolid = l_spoolid "'30221'
* NO_DIALOG = 'X'
dst_device = 'LOCL'
* PDF_DESTINATION =
* NO_BACKGROUND =
* GET_SIZE_FROM_FORMAT =
IMPORTING
pdf_bytecount = l_pdf_bytecount
* PDF_SPOOLID =
* LIST_PAGECOUNT =
* BTC_JOBNAME =
* BTC_JOBCOUNT =
* BIN_FILE =
TABLES
pdf = it_pdf_table
EXCEPTIONS
err_no_abap_spooljob = 1
err_no_spooljob = 2
err_no_permission = 3
err_conv_not_possible = 4
err_bad_destdevice = 5
user_cancelled = 6
err_spoolerror = 7
err_temseerror = 8
err_btcjob_open_failed = 9
err_btcjob_submit_failed = 10
err_btcjob_close_failed = 11
OTHERS = 12.
MOVE l_spoolid TO l_sp_id.
CALL FUNCTION 'RSPO_R_RDELETE_SPOOLREQ'
EXPORTING
spoolid = l_sp_id.
* Map PDF table into 'flat' table acording to Unicode flag
ex_pdf_table = it_pdf_table .
IF im_email_do_not IS INITIAL.
LOOP AT it_pdf_table INTO wa_pdfline.
ASSIGN wa_pdfline TO <l_xline> CASTING.
CONCATENATE pdf_xstring <l_xline> INTO pdf_xstring IN BYTE MODE.
ENDLOOP.
* get PDF xstring and convert it to BCS format
lp_pdf_size = xstrlen( pdf_xstring ).
pdf_content = cl_document_bcs=>xstring_to_solix(
ip_xstring = pdf_xstring ).
TRY.
*-------- create persistent send request ------------------------
send_request = cl_bcs=>create_persistent( ).
*-------- create and set document with attachment ---------------
*create document object from internal table with text
LOOP AT im_email_body_text INTO st_body.
APPEND st_body TO li_main_text.
ENDLOOP.
document = cl_document_bcs=>create_document(
i_type = 'RAW'
i_text = li_main_text
i_subject = im_email_subject_line ).
*add the spread sheet as attachment to document object
document->add_attachment(
i_attachment_type = 'PDF' "#EC NOTEXT
i_attachment_subject = im_attachment_name "#EC NOTEXT
i_attachment_size = lp_pdf_size "Size
i_att_content_hex = pdf_content ).
*add document object to send request
send_request->set_document( document ).
*get email addresses from table
LOOP AT im_email_address INTO st_email_addr.
APPEND st_email_addr TO li_recipient.
ENDLOOP.
*Get email addresses from Distribution list
CALL FUNCTION 'SO_DLI_READ_API1'
EXPORTING
shared_dli = 'X'
dli_id = space
dli_name = im_email_dist_name
IMPORTING
dli_data = l_dlidata
TABLES
dli_entries = li_dlientries
EXCEPTIONS
dli_not_exist = 9001
operation_no_authorization = 9002
parameter_error = 9003
x_error = 9004
OTHERS = 01.
CLEAR st_email_addr.
LOOP AT li_dlientries INTO st_dlientry.
st_email_addr-smtpadr = st_dlientry-member_adr.
st_email_addr-mail_to = 'X'.
APPEND st_email_addr TO li_recipient.
ENDLOOP.
*Get email addresses from Distribution Id
CALL FUNCTION 'SO_DLI_READ_API1'
EXPORTING
shared_dli = 'X'
dli_id = im_email_dist_id
dli_name = space
IMPORTING
dli_data = l_dlidata
TABLES
dli_entries = li_dlientries
EXCEPTIONS
dli_not_exist = 9001
operation_no_authorization = 9002
parameter_error = 9003
x_error = 9004
OTHERS = 01.
LOOP AT li_dlientries INTO st_dlientry.
st_email_addr-smtpadr = st_dlientry-member_adr.
st_email_addr-mail_to = 'X'.
APPEND st_email_addr TO li_recipient.
ENDLOOP.
*--------- add recipient (e-mail address)-----------------------
LOOP AT li_recipient INTO st_email_addr.
l_recipient = st_email_addr-smtpadr.
recipient = cl_cam_address_bcs=>create_internet_address( l_recipient ).
IF st_email_addr-mail_to = 'X'.
CLEAR l_mailcc.
CLEAR l_mailbcc.
ELSE.
IF st_email_addr-mail_cc = 'X'.
l_mailcc = 'X'.
CLEAR l_mailbcc.
ELSE.
IF st_email_addr-mail_bcc = 'X'.
l_mailbcc = 'X'.
CLEAR l_mailcc.
ENDIF.
ENDIF.
ENDIF.
TRY.
CALL METHOD send_request->add_recipient
EXPORTING
i_recipient = recipient
i_express = 'X'
i_copy = l_mailcc
i_blind_copy = l_mailbcc.
ENDTRY .
ENDLOOP.
*add recipient object to send request
*send_request->add_recipient( recipient ).
*---------- send document ---------------------------------------
send_request->send_request->set_link_to_outbox( 'X' ).
l_sent_to_all = send_request->send( i_with_error_screen = 'X' ).
COMMIT WORK.
IF l_sent_to_all IS INITIAL.
ex_send_to_all = '1'.
ELSE.
ex_send_to_all = '0'.
ENDIF.
SUBMIT rsconn01 WITH mode = 'INT'
WITH output = 'X'
AND RETURN.
* ------------ exception handling ----------------------------------
CATCH cx_bcs INTO bcs_exception.
* message i865(so) with bcs_exception->error_type.
ENDTRY.
ENDIF.
ENDMETHOD.
*———————————————————————————————————————————-*
Step5:Activate the method and class and write the below small executable test program to test it.Go to SE38 create the below program to test:
Sample Code :
*——————————————————————————————————————————-*
Please find below the sample code for the test program.
*&---------------------------------------------------------------------*
*& Report ZTP_SEND_EMAIL
*&
*&-----------------------------------------------------------------------------*
*&Short Description : This is a Test Program which calls the method *
*& 'SEND_PDF_FILE' of the Global Class 'ZCL_SEND_ATTACHMENT'*
*& and will send the email with a PDF file as an attachment.*
*&-----------------------------------------------------------------------------*
REPORT ztp_send_email.
PARAMETERS : p_email TYPE char100 DEFAULT 'hafizul.mollah@test.com'."Email ID in the format test@xxxx.com
TYPES: BEGIN OF ty_outfield,
outdata TYPE soli,
END OF ty_outfield,
BEGIN OF ty_data,
outdata TYPE ztp_text_struct,
END OF ty_data.
DATA:ls_body TYPE soli,
lt_body TYPE bcsy_text,
lt_headings TYPE soli_tab,
ls_headings TYPE ty_outfield,
ls_data TYPE ty_data,
lt_data TYPE ztp_text_tab,
ls_email TYPE ztp_smtp_struct,
lt_email TYPE ztp_smtp_tab,
l_dist_list TYPE so_obj_nam,
l_dist_list1 TYPE so_obj_id,
pdf_file TYPE rcl_bag_tline,
li_email TYPE ztp_smtp_tab,
lst_email TYPE ztp_smtp_struct,
l_return TYPE os_boolean,
li_body TYPE bcsy_text,
lst_body TYPE soli.
*----Populate Column names in the PDF file--------*
ls_headings-outdata = 'PERNR'. APPEND ls_headings TO lt_headings.
ls_headings-outdata = 'LNAME'. APPEND ls_headings TO lt_headings.
ls_headings-outdata = 'FNAME'. APPEND ls_headings TO lt_headings.
*----Populate Actual data names in the PDF file(Use Internal Table content here)--------*
ls_data-outdata = '10000001|Romo|Tony'. APPEND ls_data TO lt_data.
ls_data-outdata = '10000002|Favre|Brett'. APPEND ls_data TO lt_data.
*----Populate Email IDs here(To ,CC , Bcc etc.)--------*
ls_email-smtpadr = p_email.
ls_email-mail_to = 'X'.
APPEND ls_email TO li_email.
CLEAR : ls_email.
*ls_email-smtpadr = 'souvik.bhattacharya@test.com'.
*ls_email-mail_to = ' '.
*ls_email-mail_cc = 'X'.
*APPEND ls_email TO li_email. "
*----Populate Body of the email here--------*
lst_body = 'Hello User,'.
APPEND lst_body TO li_body. "Body of the email
CLEAR : lst_body.
lst_body = 'Please find attached the PDF file.'.
APPEND lst_body TO li_body. "Body of the email
CALL METHOD zcl_send_attachment=>send_pdf_file
EXPORTING
im_file_header_text = 'Employee Name Details'
im_email_subject_line = 'Employee Details in attached PDF file '
im_email_body_text = li_body
im_email_address = li_email
im_email_dist_name = 'DISTRIBU_LIS'
im_email_dist_id = 'DISTRIBU_LIS'
im_attachment_name = 'Employee_data.pdf'
im_file_delimeter = '|'
im_itab_1 = lt_data
im_itab_2 = lt_headings
im_email_do_not = space
IMPORTING
ex_send_to_all = l_return
EXCEPTIONS
error_transferring = 1.
IF l_return <> 0.
ELSE.
SET LOCALE LANGUAGE 'E'.
COMMIT WORK.
SUBMIT rsconn01 WITH mode = 'INT'
WITH output = 'X'
AND RETURN.
WRITE : 'Email successfully Sent'.
ENDIF.
*——————————————————————————————————————————*
Step6: Activate the program and execute it.Please change the email ID to yours one to receive the email to Lotus Notes / Outlook /Other email configured.
Execute the program and test whether the email is sent successfully or not (Check in SOST tcode):
Open the PDF file attached in the email and make sure the content is correct:
Please let me know if anyone face any issue while developing or testing it.
Thanks & Regrads,
Hafizul Mollah,
SAP ABAP Consultant @Capgemini India Pvt. Ltd.
Alert Moderator
Assigned tags
ABAP Development
abap
attachment
View more...
Related Blog Posts
Email using CL_BCS with multiple attachment in any format
By zafar karnalkar, Jul 16, 2013
How to Convert the Spool into PDF and Send to External Email
By Former Member, Oct 30, 2006
Simple BCS email Method (With/Without Attachment)
By playsuji s, Mar 27, 2012
Related Questions
We are sorry but we are currently unable to retrieve related content.
18 Comments
Former Member
May 15, 2014 at 3:11 pm
This was very useful for me. Great Content
Like(0)
Reply
Alert Moderator
Hafizul Mollah Post author
May 16, 2014 at 4:30 am
Thanks Radhika….glad to hear that it helped you…..
Like(0)
Reply
Alert Moderator
Former Member
September 3, 2014 at 2:25 am
Hi Hafizul,
This cool i want to use this too! but for my situation i am using ALV report so i already have an internal table for the details and i have to convert it to pdf frst then send it.
1. how can i use this using my table?
the code in the details is like this:
ls_data–outdata = ‘10000001|Romo|Tony’
how could i use my internal table with out looping and using concatenate?
2. i also have a traffic light status icon in my internal table, if ever the alv worked will the icon display correctly?
i’m just a noob here and also in SAP ABAP, if my question was already answered, could you kindly give me a link for this?
thank you very much!
Like(0)
Reply
Alert Moderator
Hafizul Mollah Post author
September 3, 2014 at 5:33 pm
Hello Edsel,
You might have noticed that in the method code , it is splitting the character content string by the separator give as input , so you have to prepare this special content separated by the separator and then pass that internal table as the input while calling the method and to prepare this you will have to loop in the itab and then use CONCATENATE statement.
Example : Lets say your itab(i_final , workarea : wa_final) has 3fields (matnr,maktx,werks) and separator is ‘|’. Content string table is ‘i_content’ , workarea : wa_content
Loop at i_final into wa_final.
CONCATENATE wa_final-matnr wa_final-maktx wa_final-werks into lv_string separated by ‘|’.
wa_content-content = lv_string.
append wa_content to i_content.
Endloop.
Now the content has been prepared and put into ‘i_content’ and you need to use this as content table while calling the method in your program.
Regarding traffic signal icon , as the method is treating all content as character , the special character icon should also be printed but it may not reflect the Green/Red color as it is writing the characters in spool using ‘write’ statement and pulling it from the spool.Please follow the same procedure described above and let me know if you face any issue.
Thanks & Regards,
Hafizul
Like(0)
Reply
Alert Moderator
Jānis B
September 3, 2014 at 9:21 pm
I mean no offense, but if the code in Source code _method.txt.zip really is the kind of stuff Capgemini India ships to customers… then I’m kind of lost for words
Like(0)
Reply
Alert Moderator
Matthew Billingham
September 4, 2014 at 6:32 am
Global variables prefixed with “L” in program.txt.
Field-symbols that have <f_ something. Hey! If it’s in a < > already, we know it’s a field symbol, what does the “F” add?
Itab1, itab2… very meaningful.
No modularisation… well, that can be forgiven, it makes it easier to share the code
Commented out exception handling…
Did I miss anything?
Like(0)
Reply
Alert Moderator
Jānis B
September 4, 2014 at 7:18 am
In addition:
First executable statement of method: l_field = ‘ ‘.
Commented parameters left in FM call.
Conditionless SET LOCALE LANGUAGE ‘E’ twice within 16 code lines.
LOOP AT im_itab_1 INTO wa_im_itab_1.
APPEND wa_im_itab_1 TO li_final.
ENDLOOP.
Yet another SET LOCALE LANGUAGE ‘E’, within a loop.
Yet another SET LOCALE LANGUAGE ‘E’. – I mean, why on earth not..?
Like(0)
Reply
Alert Moderator
Matthew Billingham
September 4, 2014 at 7:27 am
“SET LOCALE LANGUAGE E’
It’s the only way to be sure.
Like(0)
Reply
Alert Moderator
Former Member
September 4, 2014 at 7:35 am
Pretty soon when someone mentions JB in coffee corner, people will confuse between you and Julius.
Like(0)
Reply
Alert Moderator
Hafizul Mollah Post author
September 4, 2014 at 10:40 am
Hello all,
All these codes are from test programs and it was developed as a PoC , so both in the program and class methods no specific naming convention has been followed…I am aware all these but in the customer deliverable program the fixed naming convention is being followed stictly.
My request to all of you , please ignore the naming convention issues and also use this as basic template and enhance this as per your specific requirement and optimize it before deliver the same to the client.This is just a test program which I created to debug and test the whole thing , please do not use this blindly and it needs to be modified as per the concerned client’s requirement and company’s ABAP development naming convention.
Thanks & Regards,
Hafizul
Like(0)
Reply
Alert Moderator
Former Member
July 8, 2015 at 11:59 am
Hi, first be thanking for your work.
I have a prolem, I can´t open the pdf attachtment. it sais that the format is invalid.
I have tried to modify the language to S = Spanish but I don´t think that is the problem.
thank´s so much
Like(0)
Reply
Alert Moderator
Hafizul Mollah Post author
August 12, 2015 at 12:49 pm
Hello Javier,
I have not faced this issue even during R&D phase—–hope u have copied the same code and tried—and Adobe is also installed in ur system—-as u know we are writing to the spool and then reading from spool, so please check if the spool settings are correctly done in your system—-also can u please debug the whole thing—-starting from program, internal table data, separator then in the method where reading from spool etc. and see if where it is actually failing/giving issues/exception.
Like(0)
Reply
Alert Moderator
Fernando Iruela
December 17, 2015 at 5:21 pm
Hi,
Hafizul, thanks so much for explanation.
Javier, i face through the same problem as you, and debugging found that it is the parameter of impression “destination = ‘LOCL’“, that does not exist, but leaving it blank he takes the first valid:
CALL FUNCTION ‘GET_PRINT_PARAMETERS’
EXPORTING
immediately = ‘ ‘
no_dialog = ‘X’
layout = im_layout
IMPORTING
out_parameters = params
valid = valid.
Thanks!
Like(0)
Reply
Alert Moderator
Florin Wach
March 2, 2016 at 1:45 pm
You could also use a generic smartForm to hold your print-out (WRITE’s) to retrieve your PDF.
With that, you don’t need to go the long way round the spooler. It’s a bit faster in processing, as no file is being generated intermediatly.
Like(0)
Reply
Alert Moderator
Former Member
March 30, 2017 at 12:57 pm
Hello Hafizul Mollah,