Script to Announce Mail
Hi everyone!
I'm interesting in a script which announces the sender's name for an incoming email. I'm using Apple Mail 2.1. Can anyone help?
Thanks!
Try this.
AK
click here to open this script in your editor<pre style="font-family: 'Monaco', 'Courier New', Courier, monospace; overflow:auto; color: #222; background: #DDD; padding: 0.2em; font-size: 10px; width:400px">-- speak the sender of mail paassed by rule or selected in the Mail app
-- AK Dec 2007
using terms from application "Mail"
on perform mail action with messages theMsges
tell application "Mail"
repeat with AMessage in theMsges
set WhoSentIt to (extract name from sender of AMessage)
if (count of WhoSentIt) > 0 then say "Mail from " & WhoSentIt
end repeat
end tell
end perform mail action with messages
end using terms from
using terms from application "Mail"
on run
tell application "Mail" to set sel to selection
tell me to perform mail action with messages (sel)
end run
end using terms from
</pre>
Similar Messages
-
Script to open mail at login and then hide app
I've been messing around with apple script lately and found it useful in being able to do various tasks etc, I've even written a few basic scripts myself
I use my computer primarily at home with a wireless network and i just leave my mail app open to check my mail more easily. I have the program set up to open at login, which works and then leaves the inbox window open.
I'm wondering if there is a way with apple script to tell mail to open at login and then hide it self once it's open so that it seems like it opened in the background.
any ideas?Have you considered using the hide option in 'login items' tab in system preferences/accounts?
Go to system preferences, then to accounts, and then use the 'login items' tab with your account name. Now you can specify Mail to open as you login and then there is an option for you to hide Mail once it opens.
The net effect is that you will have Mail open once you login and then have it hide itself after login.
Hope this helps.
eviscerationer -
Script for getting mail if database is down
Hi Friends,
OS Version : IBM AIX 5,2
Oracle version : 9.2.0.7
I am executing the following script for getting mail alert if database is down. some how the script is not working
check_stat=`ps -ef|grep ${ORACLE_SID}|grep pmon|wc -l`;
oracle_num=`expr $check_stat`
if [ $oracle_num -lt 1 ]
then
exit 0
fi
# Test to see if Oracle is accepting connections
$ORACLE_HOME/bin/sqlplus -s "/as sysdba" > /tmp/check_$ORACLE_SID.ora
select name from v$database;
exit
# If not, exit and e-mail . . .
check_stat=`cat /tmp/check_$ORACLE_SID.ora|grep -i error|wc -l`;
oracle_num=`expr $check_stat`
if [ $oracle_num -ne 0 ]
then
mailx -s "$ORACLE_SID is down!" [email protected] < /tmp/check_$ORACLE_SID.ora
exit 16
fi
I am saving this as .sh file and executing at command prompt. It is just hanging, but not throwing any error.
I would like to know if there is anything to be modified in the script or please provide me any such script. Thanks in advanceHI there.
I have a script I use that works really well. It sends out an email only if the database is down and also reads an ini file to process a blackout period and a priority level of the database... High priority databases are monitored every 5 minutes and Medium priority databases every hour.
There are two scripts, the shell script and the .ini file and I have two cron entries...
Check script:_
#!/bin/ksh
# check_oracle_status.sh
# Script to check if Oracle db's are up and running.
# Script is passed a priority field and reads check_oracle_status.ini
# to determine which db's to check. If db is down an email is sent.
# Priority Levels:
# H - Checks db's with "H"igh Priority every 5 minutes (cron)
# M - Checks db's with "M"edium Priority every hour (cron)
# L - db's with "L"ow Priority currently not checked
# Script Change History:
# ======================
# October 29th, 2009 - Initial Creation
# Set environment
export SCRIPTHOME=/opt/oracle/admin/scripts
export INIFILE=$SCRIPTHOME/check_oracle_status.ini
export PRIORITY=$1
. $HOME/.profile
db=`grep -i ":$PRIORITY" $INIFILE | cut -d":" -f1`
check_database()
sqlplus <<! > $SCRIPTHOME/check.out
/ as sysdba
select * from dba_data_files;
exit
grep ORA- $SCRIPTHOME/check.out > $SCRIPTHOME/error.out
if (( $? )); then
echo ""
else
mailx -s "Oracle instance $i is currently UNAVAILABLE" +<email address>+ < $SCRIPTHOME/error.out
fi
for i in $db ; do
fields=`grep $i $INIFILE | awk -F':' '{ total = total + NF }; END {print total}'`
export ORACLE_SID=$i
if [ $fields -gt 2 ]; then
BLACKOUT_START=`grep -i "$ORACLE_SID" $INIFILE | cut -d":" -f3`
BLACKOUT_END=`grep -i "$ORACLE_SID" $INIFILE | cut -d":" -f4`
CURRENT_HOUR=`date +%H`
CHECK_BASE=YES
if [ $BLACKOUT_START -gt $BLACKOUT_END ]; then
(( $CURRENT_HOUR >= $BLACKOUT_START || $CURRENT_HOUR <= $BLACKOUT_END )) && CHECK_BASE=
else
(( $CURRENT_HOUR >= $BLACKOUT_START && $CURRENT_HOUR <= $BLACKOUT_END )) && CHECK_BASE=
fi
if [ -n "$CHECK_BASE" ]; then
check_database
fi
else
check_database
fi
done
rm $SCRIPTHOME/check.out $SCRIPTHOME/error.out
INI File:_
oracle1:L
oracle2:M:17:08
oracle3:M
oracle5:M:17:08
oracle6:H
oracle7:M:17:08
oracle8:M
oracle9:M
Where oracle1,2,3 etc is your sid
L M and H your priority level
17 is blackout start (5 PM)
08 is blackout end (8 AM)
Note: Blackout is just a start hour and an end hour and must contain both or none and my script can only process one blackout per database. I guess if you
needed a second blackout you could add another line with different times for that sid
Cron entries:_
# Check Oracle Status
# The check_oracle_status.sh script monitors "H"igh priority databases every 5 minutes
# and "M"edium priority databases every hour
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /opt/oracle/admin/scripts/check_oracle_status.sh H > /dev/null 2>&1
0 * * * * /opt/oracle/admin/scripts/check_oracle_status.sh M > /dev/null 2>&1
Not sure if you require blackouts or priority levels but this setup works great at our site.
Hope this helps. -
Script for forward mail as attachment
Hi,
I think there is no direct call for creating forward mail as attachment. I tried "forward" reply and other things.Its working fine.
Please let me know if any one have idea for creating script for apple mail "forward as attachment".hm... perhaps these two functions do what you wanna do :-/
on createmail_emlx_files_attachment_ofselection()
tell application "Mail"
-- get the mail selection
set myMessages to selection
--do it to every selected mail
repeat with m in myMessages
--get the folder where the emlx file is stored in
set mypath to quoted form of POSIX path of ((account directory of account of mailbox of m) as alias)
--get the id of that message (should be unique within each account)
set myid to id of m
--find the folder where this unique email (by id) is stored in
set myfolder to quoted form of (paragraph 1 of (do shell script "find " & mypath & " -name '" & myid & ".emlx' -exec dirname {} \\;"))
--create a compressed tar archive of this message and open this gzipped files with Apple Mail (-> attach it to a new message).
do shell script "cd " & myfolder & ";tar -rf " & myid & ".tar " & myid & ".emlx;gzip " & myid & ".tar;mv " & myid & ".tar.gz /tmp/;open -a /Applications/Mail.app /tmp/" & myid & ".tar.gz"
end repeat
end tell
end createmail_emlx_files_attachment_ofselection
on createmail_source_attachment_ofselection()
tell application "Mail"
-- get the mail selection
set myMessages to selection
--do it to every selected mail
repeat with m in myMessages
set myid to id of m
set mysource to quoted form of ((source of m) as text)
do shell script "cd /tmp/;echo " & mysource & "|cat>/tmp/" & myid & ".txt;gzip " & myid & ".txt;open -a /Applications/Mail.app " & myid & ".txt.gz"
end repeat
end tell
end createmail_source_attachment_ofselection -
Script spol to mail , and report which sends output to spools
Hi All,
Please give me
script spol to mail , and report which sends output to spool.
thaks,
babuHi,
Check the below code:
scripts through email:
*& Report ZRICHA_OTF_PDF
report zricha_otf_pdf
message-id zz.
CONSTANTS *
constants : c_x(1) type c value 'X', " For constant value
c_otf(3) type c value 'OTF', " For format
c_u(1) type c value 'U'. " Mail Option
VARIABLES *
data : v_rqident type tsp01-rqident, " For Spool Number
v_rqclient type tsp01-rqclient, " For Client
v_rqo1name type tsp01-rqo1name, " For Object name
v_spool type tsp01-rqident, " For Spool Number
v_spool1 type tsp01-rqident. " For Spool Number
FLAGS *
data : f_spool type c.
INTERNAL TABLES *
Internal table for sending mails
data: it_pdf like tline occurs 10 with header line,
it_xi_pdf like tline occurs 0 with header line,
it_html like solisti1 occurs 0 with header line,
it_xi_temp like bapiqcmime occurs 0 with header line,
it_xi_mime(255) type c occurs 0 with header line.
For sending mail
data: it_objpack like sopcklsti1 occurs 2 with header line.
Internal table for Single List with Column Length 255
data : it_objbin like solisti1 occurs 10 with header line.
Internal table for Single List with Column Length 255
data : it_objtxt like solisti1 occurs 10 with header line.
Internal table for Structure of the API Recipient List
data : it_reclist like somlreci1 occurs 5 with header line.
Structure of the API Recipient List
data: x_doc_chng like sodocchgi1.
Internal table for storing the variants
data : begin of it_variant1 occurs 0,
variant like varid-variant,
end of it_variant1.
Internal table to store variants for the programs
data: it_variant2 like it_variant1 occurs 0 with header line.
Internal table for storing the selected values
data it_return type ddshretval occurs 0 with header line.
Internal table for storing the mail-ids
data : begin of it_mailid occurs 0,
kokrs like csks-kokrs,
kostl like csks-kostl,
datbi like csks-datbi,
telx1 like csks-telx1,
end of it_mailid.
Internal table for storing the mail-ids
data : it_mailid1 like it_mailid occurs 0 with header line.
SELECTION SCREEN *
data : v_char type char50.
selection-screen begin of block b1 with frame title text-001.
select-options: s_email for v_char no intervals
lower case
no-display.
select-options: s_email1 for v_char no intervals
lower case
no-display.
selection-screen end of block b1.
selection-screen begin of block a1 with frame title text-028.
selection-screen begin of line.
parameters : p_c1 as checkbox.
selection-screen comment 3(66) text-026 for field p_c1.
selection-screen end of line.
parameters : p_set like tsp1d-papart matchcode object zh_tsp1d.
selection-screen skip 1.
parameters : p_vara1 type rs38m-selset.
selection-screen end of block a1.
selection-screen begin of block a2 with frame title text-029.
selection-screen begin of line.
parameters : p_c2 as checkbox.
selection-screen comment 3(56) text-027 for field p_c1.
selection-screen end of line.
parameters : p_set1 like tsp1d-papart matchcode object zh_tsp1d.
selection-screen skip 1.
parameters : p_vara2 type rs38m-selset.
selection-screen end of block a2.
AT SELECTION SCREEN ON VALUE REQUEST
at selection-screen on value-request for p_vara1.
For fetching the variants available for the program
perform fetch_variants.
at selection-screen on value-request for p_vara2.
For fetching the variants available for the program
perform fetch_variants1.
AT SELECTION SCREEN
at selection-screen.
For Validation
perform validation.
START OF SELECTION *
start-of-selection.
To get the output data and mail
perform fetch_data.
END OF SELECTION *
end-of-selection.
if f_spool = c_x.
message e000 with 'Spool Not Generated'(060).
endif.
*& Form fetch_data
To get the output data and mail
form fetch_data .
To send the output to spool
perform generate_spool.
endform. " fetch_data
*& Form generate_spool
To send the output to spool
form generate_spool .
data: l_params like pri_params,
l_days(1) type n value 2,
l_count(3) type n value 1,
l_valid type c,
l_valid1 type c,
l_params1 like pri_params.
data: l_device type usr01-spld.
*Get the printer name for the user
select single spld into l_device from usr01 where bname = sy-uname.
if l_device is initial.
l_device = 'LOCL'.
endif.
For report-1
if p_c1 = 'X'.
Setting the print parameters
call function 'GET_PRINT_PARAMETERS'
exporting
destination = l_device
copies = l_count
list_name = sy-uname
list_text = 'SUBMIT ... TO SAP-SPOOL'(008)
release = c_x
new_list_id = c_x
expiration = l_days
LINE_SIZE = 255
LINE_COUNT = 65
layout = p_set
sap_cover_page = space
cover_page = space
receiver = 'SAP*'(010)
department = 'System'(011)
no_dialog = c_x
importing
out_parameters = l_params
valid = l_valid.
if l_valid <> space.
clear v_spool.
Fetch the spool number b4 submit
perform fetch_recent_spool using v_spool.
Submitting the program to spool
submit rkaep000 to sap-spool
using selection-set p_vara1
spool parameters l_params
without spool dynpro
and return.
clear v_spool1.
Fetch the spool number after submit
perform fetch_recent_spool using v_spool1.
if v_spool = v_spool1.
f_spool = c_x.
if p_c2 is initial.
stop.
endif.
else.
Checking the format ( ABAP/OTF)
perform format_check tables s_email.
endif.
else.
message e000 with 'Problem in print settings'(003).
stop.
endif.
endif.
For Report-2
if p_c2 = 'X'.
Setting the print parameters
call function 'GET_PRINT_PARAMETERS'
exporting
destination = l_device
copies = l_count
list_name = sy-uname
list_text = 'SUBMIT ... TO SAP-SPOOL'(008)
release = c_x
new_list_id = c_x
expiration = l_days
LINE_SIZE = 200
LINE_COUNT = 65
layout = p_set1
sap_cover_page = space
cover_page = space
receiver = 'SAP*'(010)
department = 'System'(011)
no_dialog = c_x
importing
out_parameters = l_params1
valid = l_valid1.
if l_valid1 <> space.
clear v_spool.
Fetch the spool number b4 submit
perform fetch_recent_spool using v_spool.
Submitting the program to spool
submit gp3diehxy88snfj0391v7kf9ek7050 to sap-spool
using selection-set p_vara2
spool parameters l_params1
without spool dynpro
and return.
clear v_spool1.
Fetch the spool number after submit
perform fetch_recent_spool using v_spool1.
if v_spool = v_spool1.
message e000 with 'Spool Not Generated'(060).
stop.
endif.
Checking the format ( ABAP/OTF)
perform format_check tables s_email1.
else.
message e000 with 'Problem in print settings'(003).
stop.
endif.
endif.
endform. " generate_spool
*& Form fetch_recent_spool
Fetch the recent spool number generated
form fetch_recent_spool using p_v_spool type tsp01-rqident .
data: l_user like tsp01-rq2name.
clear : v_rqident,
v_rqclient,
v_rqo1name.
l_user = sy-uname.
Get latest Spool No
select single rqident
rqclient
rqo1name
into (v_rqident , v_rqclient , v_rqo1name)
from tsp01
where rqcretime = ( select max( rqcretime )
from tsp01
where rq2name eq l_user
and rqfinal eq '.' ).
if sy-subrc = 0 .
p_v_spool = v_rqident.
endif.
endform. " fetch_recent_spool
*& Form format_check
Checking the format ( ABAP/OTF)
form format_check tables p_s_email structure s_email.
data : l_objtype like rststype-type.
call function 'RSTS_GET_ATTRIBUTES'
exporting
authority = 'SP01'(019)
client = v_rqclient
name = v_rqo1name
part = 1
importing
objtype = l_objtype
exceptions
fb_error = 1
fb_rsts_other = 2
no_object = 3
no_permission = 4.
if sy-subrc <> 0.
message id sy-msgid type sy-msgty number sy-msgno
with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
endif.
if l_objtype(3) = c_otf.
Convert OTF Spool to PDF
perform convert_otf2pdf tables p_s_email.
else.
Convert ABAP Spool to PDF
perform convert_abap2pdf tables p_s_email.
endif.
endform. " format_check
*& Form convert_otf2pdf
Convert OTF Spool to PDF
form convert_otf2pdf tables p_p_s_email structure s_email .
clear it_pdf.
refresh it_pdf.
data : l_bytecount type i.
Fn. to get the PDF format
call function 'CONVERT_OTFSPOOLJOB_2_PDF'
exporting
src_spoolid = v_rqident
no_dialog = 'X'
importing
pdf_bytecount = l_bytecount
tables
pdf = it_pdf
exceptions
err_no_otf_spooljob = 1
err_no_spooljob = 2
err_no_permission = 3
err_conv_not_possible = 4
err_bad_dstdevice = 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.
if sy-subrc = 0.
For page format
perform page_format tables p_p_s_email.
else.
message id sy-msgid type sy-msgty number sy-msgno
with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
endif.
endform. " convert_otf2pdf
*& Form convert_abap2pdf
Convert ABAP Spool to PDF
form convert_abap2pdf tables p_p_s_email structure s_email.
clear it_pdf.
refresh it_pdf.
data : l_bytecount type i.
Fn. to convert to PDF format
call function 'CONVERT_ABAPSPOOLJOB_2_PDF'
exporting
src_spoolid = v_rqident
no_dialog = 'X'
importing
pdf_bytecount = l_bytecount
tables
pdf = it_pdf
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.
if sy-subrc = 0.
For page formatting
perform page_format tables p_p_s_email.
else.
message id sy-msgid type sy-msgty number sy-msgno
with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
endif.
endform. " convert_abap2pdf
*& Form send_mail
For sending mail
form send_mail tables mail structure s_email .
Structures and internal tables for the send data
data: objpack like sopcklsti1 occurs 2 with header line,
objhead like solisti1 occurs 1 with header line,
objbin like solisti1 occurs 0 with header line,
objtxt like solisti1 occurs 10 with header line,
reclist like somlreci1 occurs 5 with header line.
data: doc_chng like sodocchgi1,
tab_lines like sy-tabix.
Data for the status output after sending
data: sent_to_all like sonv-flag.
clear: it_reclist, it_reclist[],
it_objtxt , it_objtxt[],
it_objpack, it_objpack[],
it_objbin , it_objbin[],x_doc_chng.
loop at it_html.
objbin-line = it_html-line.
append objbin.
clear objbin.
endloop.
Create the document which is to be sent
doc_chng-obj_name = 'List'(012).
doc_chng-obj_descr = 'Mail'(013).
Heading
objtxt-line = 'Mail with pdf attachment'(014).
append objtxt.
clear objtxt.
Size
describe table objtxt lines tab_lines.
read table objtxt index tab_lines.
doc_chng-doc_size = ( tab_lines - 1 ) * 255 + strlen( objtxt ).
Fill the fields of the packing_list for the main document:
clear objpack-transf_bin.
The document needs no header (head_num = 0)
objpack-head_start = 1.
objpack-head_num = 0.
Body
objpack-body_start = 1.
objpack-body_num = tab_lines.
objpack-doc_type = 'RAW'(015).
append objpack.
Create the attachment (the list itself)
describe table objbin lines tab_lines.
Fill the fields of the packing_list for the attachment:
objpack-transf_bin = 'X'.
Header
objpack-head_start = 1.
objpack-head_num = 0.
Body
objpack-body_start = 1.
objpack-body_num = tab_lines.
objpack-doc_type = 'PDF'(016).
objpack-obj_name = 'Attachment'(017).
objpack-obj_descr = 'Mail with pdf Attachment'(018).
objpack-doc_size = tab_lines * 255.
append objpack.
*-Fill the mail recipient list
loop at mail.
reclist-receiver = mail-low.
reclist-rec_type = c_u.
append reclist.
clear: reclist,
mail.
endloop.
*-Send the document by calling the SAPoffice API1 module for sending
*-documents with attachments
call function 'SO_NEW_DOCUMENT_ATT_SEND_API1'
exporting
document_data = doc_chng
put_in_outbox = c_x
commit_work = c_x
importing
sent_to_all = sent_to_all
tables
packing_list = objpack
object_header = objhead
contents_bin = objbin
contents_txt = objtxt
receivers = reclist
exceptions
too_many_receivers = 1
document_not_sent = 2
operation_no_authorization = 4
others = 99.
case sy-subrc .
when 0.
message i000 with 'Mail has been sent successfully'(006).
when others.
message e000 with 'Problem in sending the mail'(023).
endcase.
endform. " send_mail
*& Form page_format
For page foramtting
form page_format tables email structure s_email .
data : l_lines type i,
l_temp(500) type c,
l_offset type p,
l_lineslen(2) type p,
l_mimelen(2) type p,
l_tabix like sy-tabix.
clear : it_xi_pdf,
it_xi_temp.
refresh : it_xi_pdf,
it_xi_temp.
it_xi_pdf[] = it_pdf[].
Reformat the line to 255 characters wide (code from SAP)
clear: l_temp, l_offset, it_xi_temp.
describe table it_xi_pdf lines l_lines.
describe field it_xi_pdf length l_lineslen in character mode.
describe field it_xi_temp length l_mimelen in character mode.
loop at it_xi_pdf.
l_tabix = sy-tabix.
move it_xi_pdf to l_temp+l_offset.
if l_tabix = l_lines.
l_lineslen = strlen( it_xi_pdf ).
endif.
l_offset = l_offset + l_lineslen.
if l_offset ge l_mimelen.
clear it_xi_temp.
it_xi_temp = l_temp(l_mimelen).
append it_xi_temp.
shift l_temp by l_mimelen places.
l_offset = l_offset - l_mimelen.
endif.
if l_tabix = l_lines.
if l_offset gt 0.
clear it_xi_temp.
it_xi_temp = l_temp(l_offset).
append it_xi_temp.
endif.
endif.
endloop.
clear : it_xi_mime,
it_xi_mime[].
loop at it_xi_temp.
it_xi_mime(255) = it_xi_temp-line.
append it_xi_mime.
clear it_xi_mime.
endloop.
Final Data
clear : it_html,
it_html[].
it_html[] = it_xi_mime[].
For sending mail
perform send_mail tables email.
endform. " page_format
*& Form fetch_variants
For fetching the variants available for the program
form fetch_variants .
data : l_program like rs38m-programm value 'RKAEP000',
l_vara1 type dfies-fieldname value 'P_VARA1'.
clear : it_variant1,
it_variant1[].
Get variants
perform get_variants tables it_variant1
using l_program.
F4 Help
if not it_variant1[] is initial.
perform get_f4_help tables it_variant1
using l_vara1
changing p_vara1.
else.
message e000 with 'No variants available for report1'(054).
endif.
endform. " fetch_variants
*& Form validation
For Validation
form validation .
data : l_pro1 like rs38m-programm value 'RKAEP000',
l_pro2 like rs38m-programm value 'GP3DIEHXY88SNFJ0391V7KF9EK7050',
l_c1,
l_c2.
If both check-box are unchecked
if p_c1 is initial
and p_c2 is initial.
message e000 with 'Check any one check-box'(049).
endif.
If checked without varaint
if not p_c1 is initial and p_vara1 is initial.
message e000 with 'Please give any one of the variant for report1'(055).
endif.
If checked without varaint
if not p_c2 is initial and p_vara2 is initial.
message e000 with 'Please give any one of the variant for report2'(061).
endif.
Reading the variant and fetching the mail-ids
if p_c1 = c_x.
l_c1 = '1'.
clear : s_email,
s_email[].
perform read_variants tables it_mailid
s_email
using p_vara1
l_pro1
l_c1.
if s_email[] is initial.
message e000 with 'No Id available for given Cost report1'(066).
else.
sort s_email by low.
delete adjacent duplicates from s_email comparing low.
endif.
endif.
Reading the variant and fetching the mail-ids
if p_c2 = c_x.
clear : s_email1,
s_email1[].
l_c2 = '2'.
perform read_variants tables it_mailid1
s_email1
using p_vara2
l_pro2
l_c2.
if s_email1[] is initial.
message e000 with 'No Id available for given Cost report2'(067).
else.
sort s_email1 by low.
delete adjacent duplicates from s_email1 comparing low.
endif.
endif.
endform. " validation
*& Form GET_VARIANTS
Fetching Variants
form get_variants tables p_it_variant structure it_variant1
using p_v_program type rs38m-programm.
select variant
from varid
into table p_it_variant
where report = p_v_program.
endform. " GET_VARIANTS
*& Form GET_F4_HELP
text
form get_f4_help tables p_it_variant1 structure it_variant1
using p_l_vara1 like dfies-fieldname
changing p_p_vara like p_vara1.
Fn. for Pop-Up
call function 'F4IF_INT_TABLE_VALUE_REQUEST'
exporting
retfield = p_l_vara1
value_org = 'S'
display = ' '
tables
value_tab = p_it_variant1
return_tab = it_return
exceptions
parameter_error = 1
no_values_found = 2
others = 3.
if sy-subrc = 0.
p_p_vara = it_return-fieldval.
else.
message id sy-msgid type sy-msgty number sy-msgno
with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
endif.
endform. " GET_F4_HELP
*& Form FETCH_VARIANTS1
text
form fetch_variants1 .
data : v_program1 like rs38m-programm value 'GP3DIEHXY88SNFJ0391V7KF9EK7050',
l_vara2 type dfies-fieldname value 'P_VARA2'.
clear : it_variant2,
it_variant2[].
Get Variants
perform get_variants tables it_variant2
using v_program1.
F4 Help
if not it_variant2[] is initial.
perform get_f4_help tables it_variant2
using l_vara2
changing p_vara2.
else.
message e000 with 'No variants available for report2'(050).
endif.
endform. " FETCH_VARIANTS1
*& Form read_variants
Reading the variant and fetching the mail-ids
form read_variants tables p_it_mailid structure it_mailid
p_s_email structure s_email
using p_p_vara1 like p_vara1
p_l_pro1 like rs38m-programm
p_l_c1 type c.
data : l_temp(44),
it_valutab like rsparams occurs 0 with header line.
ranges : r_cocen for csks-kostl.
Function Module to get the variant contents
call function 'RS_VARIANT_CONTENTS'
exporting
report = p_l_pro1
variant = p_p_vara1
tables
valutab = it_valutab
exceptions
variant_non_existent = 1
variant_obsolete = 2
others = 3.
if sy-subrc <> 0.
message id sy-msgid type sy-msgty number sy-msgno
with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
endif.
clear : r_cocen,
r_cocen[].
loop at it_valutab where selname = 'KOSTL'
or selname = '_C-CCTR'.
Getting the range of cost centers
if it_valutab-option = 'BT'.
r_cocen-low = it_valutab-low.
For Conversion Routine
perform conversion using r_cocen-low.
r_cocen-high = it_valutab-high.
For Conversion Routine
perform conversion using r_cocen-high.
r_cocen-option = 'BT'.
r_cocen-sign = 'I'.
append r_cocen.
clear r_cocen.
endif.
Getting the single cost centers
if it_valutab-option = 'EQ'.
r_cocen-low = it_valutab-low.
For Conversion Routine
perform conversion using r_cocen-low.
r_cocen-option = 'EQ'.
r_cocen-sign = 'I'.
append r_cocen.
clear r_cocen.
endif.
endloop.
If no cost centers
if not r_cocen[] is initial.
select kokrs
kostl
datbi
telx1
from csks
into table p_it_mailid
where kostl in r_cocen.
if p_it_mailid[] is initial.
if p_l_c1 = '1'.
message e000 with 'No IDs available for report1'(059).
elseif p_l_c1 = '2'.
message e000 with 'No IDs available for report2'(062).
endif.
endif.
Deleting the blank entries
delete p_it_mailid where telx1 = space.
clear l_temp.
read table p_it_mailid index 1.
l_temp = p_it_mailid-telx1.
data : l_check.
loop at p_it_mailid where telx1 <> l_temp.
l_check = c_x.
endloop.
For checking the unique ids
if l_check = c_x.
if p_l_c1 = '1'.
message e000 with 'No unique mail-ids for report1'(058).
elseif p_l_c1 = '2'.
message e000 with 'No unique mail-ids for report2'(065).
endif.
endif.
Populating the IDs for the cost centers
loop at p_it_mailid.
set locale language sy-langu.
translate p_it_mailid-telx1 to lower case.
set locale language space .
concatenate p_it_mailid-telx1 '@allergan.com' into l_temp.
p_s_email-low = l_temp.
p_s_email-sign = 'I'.
p_s_email-option = 'EQ'.
append p_s_email.
clear p_s_email.
endloop.
else.
if p_l_c1 = '1'.
message e000 with 'No Cost Center Available for report1'(057).
elseif p_l_c1 = '2'.
message e000 with 'No Cost Center Available for report2'(063).
endif.
endif.
endform. " read_variants
*& Form CONVERSION
For Conversion Routine
form conversion using p_it_valutab_low type c.
call function 'CONVERSION_EXIT_ALPHA_INPUT'
exporting
input = p_it_valutab_low
importing
output = p_it_valutab_low.
endform. " CONVERSION
REPORT Z_RMTIWARI_SEND_SPOOL_MAIL_ATT .
PARAMETERS : P_SPOOL TYPE TSP01-RQIDENT OBLIGATORY .
PARAMETERS : P_MAIL TYPE char100 OBLIGATORY .
TYPES : TY_LINE type string.
DATA: IT_ATTACHMENT TYPE soli OCCURS 0 WITH HEADER LINE.
DATA: IT_ATTACHMENT_LONG TYPE TY_LINE OCCURS 0 WITH HEADER LINE.
DATA: LV_PDF_SIZE type i.
DATA: LT_PDF type standard table of tline with header line.
PERFORM SEND_EMAIL USING P_SPOOL P_MAIL.
FORM send_email
--> X_SPOOL_ID
--> X_EMAIL
FORM send_email USING X_SPOOL_ID X_EMAIL.
DATA: LT_OBJPACK LIKE sopcklsti1 OCCURS 2 WITH HEADER LINE,
LT_OBJHEAD LIKE solisti1 OCCURS 1 WITH HEADER LINE,
LT_OBJBIN LIKE solisti1 OCCURS 10 WITH HEADER LINE,
LT_OBJTXT LIKE solisti1 OCCURS 10 WITH HEADER LINE,
LT_RECLIST LIKE somlreci1 OCCURS 5 WITH HEADER LINE,
LV_DOCUMENT_DATA TYPE sodocchgi1.
DATA: L_ATT_LINES TYPE i.
DATA : LV_SPOOL_DESC(68) type c.
CHECK NOT ( X_EMAIL IS INITIAL ).
CLEAR: LT_RECLIST, LT_RECLIST[],
LT_OBJHEAD, LT_OBJHEAD[],
LT_OBJTXT, LT_OBJTXT[],
LT_OBJBIN, LT_OBJBIN[],
LT_OBJPACK, LT_OBJPACK[].
CLEAR LV_DOCUMENT_DATA.
Read spool and get the pdf internal table and name of spool
PERFORM READ_SPOOL USING X_SPOOL_ID LV_SPOOL_DESC.
CHECK NOT ( LT_PDF[] IS INITIAL ).
Convert pdf itab to 255 line itab.
data :LV_COUNTER type i.
data :LV_FROM type i.
loop at LT_PDF.
translate LT_PDF using ' ~' .
concatenate IT_ATTACHMENT_LONG LT_PDF into it_attachment_long.
endloop.
translate IT_ATTACHMENT_LONG using '~ ' .
append IT_ATTACHMENT_LONG.
clear : LV_COUNTER.
DO.
LV_COUNTER = strlen( IT_ATTACHMENT_LONG ).
if LV_COUNTER ge 255.
IT_ATTACHMENT = IT_ATTACHMENT_LONG(255).
append IT_ATTACHMENT.
SHIFT IT_ATTACHMENT_LONG by 255 places.
else.
IT_ATTACHMENT = IT_ATTACHMENT_LONG(lv_counter).
append IT_ATTACHMENT.
exit.
endif.
ENDDO.
Body of email
MOVE 'Email sent to you from SAP' TO LT_OBJTXT.
APPEND LT_OBJTXT.
LV_DOCUMENT_DATA-obj_name = 'SpoolMail'.
Title of the email as spool name
LV_DOCUMENT_DATA-obj_descr = LV_SPOOL_DESC.
LV_DOCUMENT_DATA-sensitivty = 'O'.
LV_DOCUMENT_DATA-expiry_dat = SY-datum + 15.
LV_DOCUMENT_DATA-doc_size = STRLEN( LT_OBJTXT ).
e-mail body
CLEAR LT_OBJPACK.
LT_OBJPACK-head_start = 1.
LT_OBJPACK-head_num = 0.
LT_OBJPACK-body_start = 1.
LT_OBJPACK-body_num = 1.
LT_OBJPACK-doc_type = 'RAW'.
LT_OBJPACK-doc_size = STRLEN( LT_OBJTXT ).
APPEND LT_OBJPACK.
For e-mail attachment
DESCRIBE TABLE IT_ATTACHMENT LINES L_ATT_LINES.
READ TABLE IT_ATTACHMENT INDEX L_ATT_LINES.
CLEAR LT_OBJPACK.
LT_OBJPACK-transf_bin = 'X'.
LT_OBJPACK-head_start = 1.
LT_OBJPACK-head_num = 1.
LT_OBJPACK-body_start = 1.
LT_OBJPACK-body_num = L_ATT_LINES.
LT_OBJPACK-doc_type = 'PDF'.
LT_OBJPACK-obj_name = 'email'.
LT_OBJPACK-obj_descr = LV_SPOOL_DESC.
LT_OBJPACK-doc_size = ( 255 * ( L_ATT_LINES - 1 ) ) + STRLEN( IT_ATTACHMENT-line ).
APPEND LT_OBJPACK.
make recipient list
LT_RECLIST-receiver = X_EMAIL.
LT_RECLIST-rec_type = 'B'. "To external email id
APPEND LT_RECLIST.
send mail with attachment
CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
EXPORTING
document_data = LV_DOCUMENT_DATA
put_in_outbox = 'X'
TABLES
packing_list = LT_OBJPACK
object_header = LT_OBJHEAD
contents_bin = IT_ATTACHMENT
contents_txt = LT_OBJTXT
receivers = LT_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.
write:/ 'Message sent'.
else.
write:/ 'Error encountered'.
endif.
ENDFORM. " send_email
*& Form read_spool
FORM read_spool USING X_SPOOL_ID Y_SPOOL_DESC.
DATA : LV_SPOOL_TYPE TYPE TSP01-RQDOCTYPE.
SELECT SINGLE RQDOCTYPE RQTITLE
INTO (lv_spool_type, y_spool_desc)
FROM TSP01
WHERE RQIDENT eq X_SPOOL_ID.
IF Y_SPOOL_DESC IS INITIAL.
concatenate 'Spool-' X_SPOOL_ID into Y_SPOOL_DESC.
ENDIF.
IF LV_SPOOL_TYPE eq 'LIST'. " If spool is a list
CALL FUNCTION 'CONVERT_ABAPSPOOLJOB_2_PDF'
EXPORTING
SRC_SPOOLID -
Hi i need script to do flowing things
A script that will enable me to highlight an email in Apple's Mail.app and then automatically add the sender of that email to a group of my choosing in Address Book.
thanks in AdvanceTry this improved version of the previous script:
*tell application "Mail" to set theSelection to selection*
*if theSelection is {} then return beep 2*
*if length of theSelection = 1 then*
* set thePrompt to "Select the group(s) to which to add the sender of the selected message."*
else
* set thePrompt to "Select the group(s) to which to add the senders of the selected messages."*
*end if*
*tell application "Address Book" to set theList to name of groups*
*set R to choose from list theList with prompt thePrompt with multiple selections allowed*
*if R is false then return*
*tell application "Mail"*
activate
* set theSenders to {}*
* repeat with thisMessage in theSelection*
* set theSender to sender of thisMessage*
* tell me to set P to offset of "<" in theSender*
* if P > 0 then set theSender to text (P + 1) through -2 of theSender*
* copy theSender to the end of theSenders*
* end repeat*
* tell application "System Events" to keystroke "y" using {shift down, command down}*
*end tell*
*tell application "Address Book"*
activate
* repeat with thisSender in theSenders*
* delay 0.1*
* set thePersons to (people whose value of emails contains (thisSender as text))*
* if (count thePersons) = 1 then*
* repeat with theGroupName in items of R*
* add (item 1 of thePersons) to group theGroupName*
* end repeat*
else
* repeat with theGroupName in items of R*
* repeat with thisPerson in thePersons*
* add thisPerson to group theGroupName*
* end repeat*
* end repeat*
* end if*
* end repeat*
save
* set selected of group theGroupName to true*
* tell application "System Events" to keystroke "0" using {command down}*
*end tell* -
How can send a script as a mail.
Hi
this is fazil.
Please tell me any body How can send a script as a mail.
Thanks & Regards
Fazil
[email protected]Hi Fazil,
First convert your script to Smartform and then use this type of coding to mail it.
Check this code.
REPORT zptpfrm202p_pogr_pr_instr MESSAGE-ID zmm.
TABLES *
Database table made for getting information about PRINTPREVIEW and
PRINT command more than one times
TABLES: zgr_table.
TYPE-POOLS:syscr.
GLOBAL TYPE DECLARATION *
DATA: zdoc_output_info TYPE ssfcrespd, "SF:Return Document Inf.
zjob_output_info TYPE ssfcrescl, "SF:Return value at end of
form printing
i_control TYPE ssfctrlop ,
i_output_options TYPE ssfcompop,
zjob_output_opts TYPE ssfcresop. "SF:Return value at start
of form printing
*This internal table is used for storing Document Segment: Material
DATA: BEGIN OF i_mseg.
INCLUDE STRUCTURE mseg.
DATA: END OF i_mseg.
This internal table is used for storing Header: Material Document
DATA: BEGIN OF i_mkpf.
INCLUDE STRUCTURE mkpf.
DATA: END OF i_mkpf.
*Variables
DATA flag(1) TYPE c.
DATA: vfile TYPE string.
SELECTION-SCREEN *
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-000.
PARAMETERS:p_mblnr TYPE mkpf-mblnr OBLIGATORY MATCHCODE OBJECT zganesh,
p_mjahr TYPE mkpf-mjahr OBLIGATORY MATCHCODE OBJECT zganesh1,
p_zeile TYPE mseg-zeile OBLIGATORY MATCHCODE OBJECT zganesh2.
SELECTION-SCREEN END OF BLOCK b1.
SELECTION-SCREEN BEGIN OF BLOCK b2 WITH FRAME TITLE text-001.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN POSITION 10.
PARAMETER:r_disp RADIOBUTTON GROUP g1 USER-COMMAND u1 DEFAULT 'X'.
SELECTION-SCREEN:COMMENT 15(10) text-002 .
SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN POSITION 10.
PARAMETERS: r_down RADIOBUTTON GROUP g1.
SELECTION-SCREEN:COMMENT 15(10) text-003.
*PARAMETERS: v_file LIKE rlgrap-filename .
*SELECTION-SCREEN:COMMENT 70(50) text-005.
SELECTION-SCREEN END OF LINE.
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN POSITION 10.
PARAMETERS: r_print RADIOBUTTON GROUP g1 .
SELECTION-SCREEN:COMMENT 15(10) text-004.
SELECTION-SCREEN END OF LINE.
PARAMETERS: v_file LIKE rlgrap-filename MODIF ID g12.
SELECTION-SCREEN END OF BLOCK b2.
AT SELECTION-SCREEN ON VALUE-REQUEST FOR v_file.
DATA : wlv_field_name LIKE dynpread-fieldname,
wlv_file_name LIKE ibipparms-path.
wlv_field_name = v_file.
CALL FUNCTION 'F4_FILENAME'
EXPORTING
field_name = wlv_field_name
IMPORTING
file_name = wlv_file_name.
IF sy-subrc EQ 0.
vfile = wlv_file_name.
v_file = wlv_file_name.
ENDIF.
AT SELECTION-SCREEN OUTPUT.
LOOP AT SCREEN.
IF screen-name = 'V_FILE'.
IF r_disp EQ 'X' OR r_print EQ 'X'.
screen-input = 0.
ELSE.
screen-input = '1'.
ENDIF.
MODIFY SCREEN.
ENDIF.
ENDLOOP.
START-OF-SELECTION EVENT *
START-OF-SELECTION.
CALLING CONVERSION FUNCTION MODULE 'CONVERSION_EXIT_ALPHA_INPUT' *
*Conversion function module for appending 00 befor MBLNR FIELD
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
EXPORTING
input = p_mblnr
IMPORTING
output = p_mblnr.
Call subroutine for fetching data from database
PERFORM get_data.
END-OF-SELECTION EVENT *
END-OF-SELECTION.
Call subroutine for calling and processing smartform
PERFORM call_smartform.
*& Form get_data
Subroutine for fetching data from database
FORM get_data .
Fetching data from MKPF table with using parameters MBLNR and MJAHR
SELECT SINGLE * FROM mkpf
INTO i_mkpf
WHERE mblnr = p_mblnr
AND mjahr = p_mjahr.
IF sy-subrc EQ 0.
Fetching data from MSEG with using parameters MBLNR,ZEILE and MJAHR
SELECT SINGLE * FROM mseg
INTO i_mseg
WHERE mblnr = i_mkpf-mblnr
AND mjahr = i_mkpf-mjahr
AND zeile = p_zeile.
IF sy-subrc NE 0.
CLEAR i_mseg.
ENDIF.
ELSE.
MESSAGE i000.
EXIT.
ENDIF.
ENDFORM. " get_data
*& Form call_smartform
Subroutine for calling smartform
FORM call_smartform .
Local template used in the processing output of smartform
TYPES: BEGIN OF lt_ztable,
mandt TYPE sy-mandt,
mblnr TYPE mseg-mblnr,
flag(1) TYPE c,
END OF lt_ztable.
CONSTANTS: c_x(1) TYPE c VALUE 'X'.
Workarea
DATA: lw_ztable TYPE lt_ztable.
*Variable used in the smartform
DATA: lv_form(30) TYPE c,
lv_fm_name(30) TYPE c.
lv_form = 'ZPTPFRM202L_POGR'.
*Calling function module SSF_FUNCTION_MODULE_NAME which gives new name
*to the function module that will generated by smartform.
CALL FUNCTION 'SSF_FUNCTION_MODULE_NAME'
EXPORTING
formname = lv_form
IMPORTING
fm_name = lv_fm_name
EXCEPTIONS
no_form = 1
no_function_module = 2
OTHERS = 3.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
*Calling function module that will be generated by smartform
IF r_disp = c_x.
i_output_options-tdimmed = space.
i_output_options-tdnewid = c_x.
i_output_options-tddest = 'LOCL'.
i_control-no_dialog = 'X'.
i_control-preview = 'X'.
ELSEIF r_print = c_x.
i_output_options-tdimmed = c_x.
i_output_options-tddest = 'LOCL'.
i_control-no_dialog = c_x.
ELSE.
i_output_options-tdimmed = space.
i_output_options-tdnewid = c_x.
i_output_options-tddest = 'LOCL'.
i_control-getotf = 'X'.
i_control-preview = space.
i_control-no_dialog = c_x.
flag = c_x.
ENDIF.
CALL FUNCTION lv_fm_name
EXPORTING
control_parameters = i_control
output_options = i_output_options
user_settings = space
zmkpf = i_mkpf
zmseg = i_mseg
IMPORTING
document_output_info = zdoc_output_info
job_output_info = zjob_output_info
job_output_options = zjob_output_opts
EXCEPTIONS
formatting_error = 1
internal_error = 2
send_error = 3
user_canceled = 4
OTHERS = 5.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
Modify the database table if it found the print command
IF zjob_output_opts-tdpreview NE c_x.
lw_ztable-mandt = sy-mandt.
lw_ztable-mblnr = p_mblnr.
lw_ztable-flag = c_x.
MODIFY zgr_table FROM lw_ztable.
CLEAR lw_ztable.
ENDIF.
IF flag EQ c_x.
DATA: li_lines LIKE tline OCCURS 100 WITH HEADER LINE.
DATA: lv_file TYPE string,
lbin_fsiz TYPE i.
lv_file = v_file.
CALL FUNCTION 'CONVERT_OTF'
EXPORTING
format = 'PDF'
IMPORTING
bin_filesize = lbin_fsiz
TABLES
otf = zjob_output_info-otfdata
lines = li_lines
EXCEPTIONS
err_max_linewidth = 1
err_format = 2
err_conv_not_possible = 3
err_bad_otf = 4
OTHERS = 5.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
CALL FUNCTION 'GUI_DOWNLOAD'
EXPORTING
bin_filesize = lbin_fsiz
filename = lv_file
filetype = 'BIN'
TABLES
data_tab = li_lines
EXCEPTIONS
file_write_error = 1
no_batch = 2
gui_refuse_filetransfer = 3
invalid_type = 4
no_authority = 5
unknown_error = 6
header_not_allowed = 7
separator_not_allowed = 8
filesize_not_allowed = 9
header_too_long = 10
dp_error_create = 11
dp_error_send = 12
dp_error_write = 13
unknown_dp_error = 14
access_denied = 15
dp_out_of_memory = 16
disk_full = 17
dp_timeout = 18
file_not_found = 19
dataprovider_exception = 20
control_flush_error = 21
OTHERS = 22.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
ENDIF.
ENDFORM. " call_smartform
Hope this resolves your query.
Reward all the helpful answers.
Regards -
Need Help on powershell Script to send mails in different languages
Hello, Just wanted to use the script below to remind users of password expiry date (I got it from internet New-Passwordreminder.ps1). We have companies in many countries, so the email should be in the language of that country. So since our users are in different
OU's according to countries, I thought some one could help me edit this script and say if the user is in AB ou then email in english will be sent, if in BC ou then the email will be in Russian....So in the script I will have all the languages I need
to have written.
<#
.SYNOPSIS
Notifies users that their password is about to expire.
.DESCRIPTION
Let's users know their password will soon expire. Details the steps needed to change their password, and advises on what the password policy requires. Accounts for both standard Default Domain Policy based password policy and the fine grain
password policy available in 2008 domains.
.NOTES
Version : v2.6 - See changelog at
http://www.ehloworld.com/596
Wish list : Better detection of Exchange server
: Set $DaysToWarn automatically based on Default Domain GPO setting
: Description for scheduled task
: Verify it's running on R2, as apparently only R2 has the AD commands?
: Determine password policy settings for FGPP users
: better logging
Rights Required : local admin on server it's running on
Sched Task Req'd : Yes - install mode will automatically create scheduled task
Lync Version : N/A
Exchange Version : 2007 or later
Author : M. Ali (original AD query), Pat Richard, Exchange MVP
Email/Blog/Twitter :
[email protected] http://www.ehloworld.com @patrichard
Dedicated Post :
http://www.ehloworld.com/318
Disclaimer : You running this script means you won't blame me if this breaks your stuff.
Info Stolen from : (original)
http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
: (date)
http://technet.microsoft.com/en-us/library/ff730960.aspx
: (calculating time)
http://blogs.msdn.com/b/powershell/archive/2007/02/24/time-till-we-land.aspx
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/23fc5ffb-7cff-4c09-bf3e-2f94e2061f29/
http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
: (password decryption)
http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/f90bed75-475e-4f5f-94eb-60197efda6c6/
: (determine per user fine grained password settings)
http://technet.microsoft.com/en-us/library/ee617255.aspx
.LINK
http://www.ehloworld.com/318
.INPUTS
None. You cannot pipe objects to this script
.PARAMETER Demo
Runs the script in demo mode. No emails are sent to the user(s), and onscreen output includes those who are expiring soon.
.PARAMETER Preview
Sends a sample email to the user specified. Usefull for testing how the reminder email looks.
.PARAMETER PreviewUser
User name of user to send the preview email message to.
.PARAMETER Install
Create the scheduled task to run the script daily. It does NOT create the required Exchange receive connector.
.EXAMPLE
.\New-PasswordReminder.ps1
Description
Searches Active Directory for users who have passwords expiring soon, and emails them a reminder with instructions on how to change their password.
.EXAMPLE
.\New-PasswordReminder.ps1 -demo
Description
Searches Active Directory for users who have passwords expiring soon, and lists those users on the screen, along with days till expiration and policy setting
.EXAMPLE
.\New-PasswordReminder.ps1 -Preview -PreviewUser [username]
Description
Sends the HTML formatted email of the user specified via -PreviewUser. This is used to see what the HTML email will look like to the users.
.EXAMPLE
.\New-PasswordReminder.ps1 -install
Description
Creates the scheduled task for the script to run everyday at 6am. It will prompt for the password for the currently logged on user. It does NOT create the required Exchange receive connector.
#>
#Requires -Version 2.0
[cmdletBinding(SupportsShouldProcess = $true)]
param(
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[switch]$Demo,
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[switch]$Preview,
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[switch]$Install,
[parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
[string]$PreviewUser
Write-Verbose "Setting variables"
[string]$Company = "Contoso Ltd"
[string]$OwaUrl = "https://mail.contoso.com"
[string]$PSEmailServer = "10.9.0.11"
[string]$EmailFrom = "Help Desk <[email protected]>"
[string]$HelpDeskPhone = "(586) 555-1010"
[string]$HelpDeskURL = "https://intranet.contoso.com/"
[string]$TranscriptFilename = $MyInvocation.MyCommand.Name + " " + $env:ComputerName + " {0:yyyy-MM-dd hh-mmtt}.log" -f (Get-Date)
[int]$global:UsersNotified = 0
[int]$DaysToWarn = 14
[string]$ImagePath = "http://www.contoso.com/images/new-passwordreminder.ps1"
[string]$ScriptName = $MyInvocation.MyCommand.Name
[string]$ScriptPathAndName = $MyInvocation.MyCommand.Definition
[string]$ou
[string]$DateFormat = "d"
if ($PreviewUser){
$Preview = $true
Write-Verbose "Defining functions"
function Set-ModuleStatus {
[cmdletBinding(SupportsShouldProcess = $true)]
param (
[parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, HelpMessage = "No module name specified!")]
[string]$name
if(!(Get-Module -name "$name")) {
if(Get-Module -ListAvailable | ? {$_.name -eq "$name"}) {
Import-Module -Name "$name"
# module was imported
return $true
} else {
# module was not available (Windows feature isn't installed)
return $false
}else {
# module was already imported
return $true
} # end function Set-ModuleStatus
function Remove-ScriptVariables {
[cmdletBinding(SupportsShouldProcess = $true)]
param($path)
$result = Get-Content $path |
ForEach { if ( $_ -match '(\$.*?)\s*=') {
$matches[1] | ? { $_ -notlike '*.*' -and $_ -notmatch 'result' -and $_ -notmatch 'env:'}
ForEach ($v in ($result | Sort-Object | Get-Unique)){
Remove-Variable ($v.replace("$","")) -ErrorAction SilentlyContinue
} # end function Get-ScriptVariables
function Install {
[cmdletBinding(SupportsShouldProcess = $true)]
param()
http://technet.microsoft.com/en-us/library/cc725744(WS.10).aspx
$error.clear()
Write-Host "Creating scheduled task `"$ScriptName`"..."
$TaskPassword = Read-Host "Please enter the password for $env:UserDomain\$env:UserName" -AsSecureString
$TaskPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($TaskPassword))
# need to fix the issue with spaces in the path
schtasks /create /tn $ScriptName /tr "$env:windir\system32\windowspowershell\v1.0\powershell.exe -psconsolefile '$env:ExchangeInstallPath\Bin\exshell.psc1' -command $ScriptPathAndName" /sc Daily /st 06:00 /ru $env:UserDomain\$env:UserName /rp
$TaskPassword | Out-Null
if (!($error)){
Write-Host "done!" -ForegroundColor green
}else{
Write-Host "failed!" -ForegroundColor red
exit
} # end function Install
function Get-ADUserPasswordExpirationDate {
[cmdletBinding(SupportsShouldProcess = $true)]
Param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, HelpMessage = "Identity of the Account")]
[Object]$accountIdentity
PROCESS {
Write-Verbose "Getting the user info for $accountIdentity"
$accountObj = Get-ADUser $accountIdentity -properties PasswordExpired, PasswordNeverExpires, PasswordLastSet, name, mail
# Make sure the password is not expired, and the account is not set to never expire
Write-Verbose "verifying that the password is not expired, and the user is not set to PasswordNeverExpires"
if (((!($accountObj.PasswordExpired)) -and (!($accountObj.PasswordNeverExpires))) -or ($PreviewUser)) {
Write-Verbose "Verifying if the date the password was last set is available"
$passwordSetDate = $accountObj.PasswordLastSet
if ($passwordSetDate -ne $null) {
$maxPasswordAgeTimeSpan = $null
# see if we're at Windows2008 domain functional level, which supports granular password policies
Write-Verbose "Determining domain functional level"
if ($global:dfl -ge 4) { # 2008 Domain functional level
$accountFGPP = Get-ADUserResultantPasswordPolicy $accountObj
if ($accountFGPP -ne $null) {
$maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge
} else {
$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
} else { # 2003 or ealier Domain Functional Level
$maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
if ($maxPasswordAgeTimeSpan -eq $null -or $maxPasswordAgeTimeSpan.TotalMilliseconds -ne 0) {
$DaysTillExpire = [math]::round(((New-TimeSpan -Start (Get-Date) -End ($passwordSetDate + $maxPasswordAgeTimeSpan)).TotalDays),0)
if ($preview){$DaysTillExpire = 1}
if ($DaysTillExpire -le $DaysToWarn){
Write-Verbose "User should receive email"
$PolicyDays = [math]::round((($maxPasswordAgeTimeSpan).TotalDays),0)
if ($demo) {Write-Host ("{0,-25}{1,-8}{2,-12}" -f $accountObj.Name, $DaysTillExpire, $PolicyDays)}
# start assembling email to user here
$EmailName = $accountObj.Name
$DateofExpiration = (Get-Date).AddDays($DaysTillExpire)
$DateofExpiration = (Get-Date($DateofExpiration) -f $DateFormat)
Write-Verbose "Assembling email message"
[string]$emailbody = @"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<table id="email" border="0" cellspacing="0" cellpadding="0" width="655" align="center">
<tr>
<td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="28" align="absMiddle">
if ($HelpDeskURL){
$emailbody += @"
<font style="font-size: 10px; color: #000000; line-height: 16px; font-family: Verdana, Arial, Helvetica, sans-serif">If this e-mail does not appear properly, please <a href="$HelpDeskURL" style="font-weight:
bold; font-size: 10px; color: #cc0000; font-family: verdana, arial, helvetica, sans-serif; text-decoration: underline">click here</a>.</font>
$emailbody += @"
</td>
</tr>
<tr>
if ($HelpDeskURL){
$emailbody += @"
<td height="121" align="left" valign="bottom"><a href="$HelpDeskURL"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif"
width="655" height="121"></a></td>
}else{
$emailbody += @"
<td height="121" align="left" valign="bottom"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif" width="655" height="121"></td>
$emailbody += @"
</tr>
<tr>
<td>
<table id="body" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
height="50"></td>
<td><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="106"></td>
<td id="text" width="572" align="left" valign="top" style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif">
if ($DaysTillExpire -le 1){
$emailbody += @"
<div align='center'>
<table border='0' cellspacing='0' cellpadding='0' style='width:510px; background-color: white; border: 0px;'>
<tr>
<td align='right'><img width='36' height='28' src='$ImagePath/image001b.gif' alt='Description: $ImagePath/image001b.gif'></td>
<td style="font-family: verdana; background: #E12C10; text-align: center; padding: 0px; font-size: 9.0pt; color: white">ALERT: You must change your password today or you will be locked out!</td>
<td align='left'><img border='0' width='14' height='28' src='$ImagePath/image005b.gif' alt='Description: $ImagePath/image005b.gif'></td>
</tr>
</table>
</div>
$emailbody += @"
<p style="font-weight: bold">Hello, $EmailName,</p>
<p>It's change time again! Your $company password expires in <span style="background-color: red; color: white; font-weight: bold;"> $DaysTillExpire </span> day(s), on $DateofExpiration.</p>
<p>Please use one of the methods below to update your password:</p>
<ol>
<li>$company office computers and Terminal Server users: You may update your password on your computer by pressing Ctrl-Alt-Delete and selecting 'Change Password' from the available options. If you use a $company laptop in addition
to a desktop PC, be sure and read #3 below.</li>
<li>Remote Outlook Client, Mac, and/or Outlook Web App users: If you only access our email system, please use the following method to easily change your password:</li>
<ul>
<li>Log into <a href="$owaurl">Outlook Web App</a> using Internet Explorer (PC) or Safari or Firefox (Mac).</li>
<li>Click on the Options button in the upper right corner of the page.</li>
<li>Select the "Change Password" link to change your password.</li>
<li>Enter your current password, then your new password twice, and click Save</li>
<li><span style="font-weight: bold">NOTE:</span> You will now need to use your new password when logging into Outlook Web App, Outlook 2010, SharePoint, Windows Mobile (ActiveSync) devices, etc. Blackberry
Enterprise Users (BES) will not need to update their password. Blackberry Internet Service (BIS) users will be required to use their new password on their device.</li>
</ul>
<li>$company issued laptops: If you have been issued a $company laptop, you must be in a corporate office and directly connected to the company network to change your password. If you also use a desktop PC in the office, you must
remember to always update your domain password on the laptop first. Your desktop will automatically use the new password.</li>
<ul>
<li>Log in on laptop</li>
<li>Press Ctrl-Alt-Delete and select 'Change Password' from the available options.</li>
<li>Make sure your workstation (if you have one) has been logged off any previous sessions so as to not cause conflict with your new password.</li>
</ul>
</ol>
<p>Think you've got a complex password? Run it through the <a href="The">http://www.passwordmeter.com/">The Password Meter</a></p>
<p>Think your password couldn't easily be hacked? See how long it would take: <a href="How">http://howsecureismypassword.net/">How Secure Is My Password</a></p>
<p>Remember, if you do not change your password before it expires on $DateofExpiration, you will be locked out of all $company Computer Systems until an Administrator unlocks your account.</p>
<p>If you are traveling or will not be able to bring your laptop into the office before your password expires, please call the number below for additional instructions.</p>
<p>You will continue to receive these emails daily until the password is changed or expires.</p>
<p>Thank you,<br />
The $company Help Desk<br />
$HelpDeskPhone</p>
if ($accountFGPP -eq $null){
$emailbody += @"
<table style="background-color: #dedede; border: 1px solid black">
<tr>
<td style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif"><b>$company Password Policy</b>
<ul>
<li>Your password must have a minimum of a $MinPasswordLength characters.</li>
<li>You may not use a previous password.</li>
<li>Your password must not contain parts of your first, last, or logon name.</li>
<li>Your password must be changed every $PolicyDays days.</li>
if ($PasswordComplexity){
Write-Verbose "Password complexity"
$emailbody += @"
<li>Your password requires a minimum of two of the following three categories:</li>
<ul>
<li>1 upper case character (A-Z)</li>
<li>1 lower case character (a-z)</li>
<li>1 numeric character (0-9)</li>
</ul>
$emailbody += @"
<li>You may not reuse any of your last $PasswordHistory passwords</li>
</ul>
</td>
</tr>
</table>
$emailbody += @"
</td>
<td width="49" align="left" valign="top"><img src="$ImagePath/spacer50.gif" alt="" width="49" height="50"></td>
<td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
height="50"></td>
</tr>
</table>
<table id="footer" border="0" cellspacing="0" cellpadding="0" width="655">
<tr>
<td><img src="$ImagePath/footer.gif" alt="Description: $ImagePath/footer.gif" width="655" height="81"></td>
</tr>
</table>
<table border="0" cellspacing="0" cellpadding="0" width="655" align="center">
<tr>
<td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
<td align="middle" valign="top"><font face="Verdana" size="1" color="#000000"><p>This email was sent by an automated process.
if ($HelpDeskURL){
$emailbody += @"
If you would like to comment on it, please visit <a href="$HelpDeskURL"><font color="#ff0000"><u>click here</u></font></a>
$emailbody += @"
</p><p style="color: #009900;"><font face="Webdings" size="4">P</font> Please consider the environment before printing this email.</p></font>
</td>
<td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
if (!($demo)){
$emailto = $accountObj.mail
if ($emailto){
Write-Verbose "Sending demo message to $emailto"
Send-MailMessage -To $emailto -Subject "Your password expires in $DaysTillExpire day(s)" -Body $emailbody -From $EmailFrom -Priority High -BodyAsHtml
$global:UsersNotified++
}else{
Write-Verbose "Can not email this user. Email address is blank"
} # end function Get-ADUserPasswordExpirationDate
if ($install){
Write-Verbose "Install mode"
Install
Write-Verbose "Checking for ActiveDirectory module"
if ((Set-ModuleStatus ActiveDirectory) -eq $false){
$error.clear()
Write-Host "Installing the Active Directory module..." -ForegroundColor yellow
Set-ModuleStatus ServerManager
Add-WindowsFeature RSAT-AD-PowerShell
if ($error){
Write-Host "Active Directory module could not be installed. Exiting..." -ForegroundColor red;
if ($transcript){Stop-Transcript}
exit
Write-Verbose "Getting Domain functional level"
$global:dfl = (Get-AdDomain).DomainMode
# Get-ADUser -filter * -properties PasswordLastSet,EmailAddress,GivenName -SearchBase "OU=Users,DC=domain,DC=test" |foreach {
if (!($PreviewUser)){
if ($ou){
Write-Verbose "Filtering users to $ou"
$users = Get-AdUser -filter * -SearchScope subtree -SearchBase $ou -ResultSetSize $null
}else{
$users = Get-AdUser -filter * -ResultSetSize $null
}else{
Write-Verbose "Preview mode"
$users = Get-AdUser $PreviewUser
if ($demo){
Write-Verbose "Demo mode"
# $WhatIfPreference = $true
Write-Host "`n"
Write-Host ("{0,-25}{1,-8}{2,-12}" -f "User", "Expires", "Policy") -ForegroundColor cyan
Write-Host ("{0,-25}{1,-8}{2,-12}" -f "========================", "=======", "===========") -ForegroundColor cyan
Write-Verbose "Setting event log configuration"
$evt = new-object System.Diagnostics.EventLog("Application")
$evt.Source = $ScriptName
$infoevent = [System.Diagnostics.EventLogEntryType]::Information
$EventLogText = "Beginning processing"
$evt.WriteEntry($EventLogText,$infoevent,70)
Write-Verbose "Getting password policy configuration"
$DefaultDomainPasswordPolicy = Get-ADDefaultDomainPasswordPolicy
[int]$MinPasswordLength = $DefaultDomainPasswordPolicy.MinPasswordLength
# this needs to look for FGPP, and then default to this if it doesn't exist
[bool]$PasswordComplexity = $DefaultDomainPasswordPolicy.ComplexityEnabled
[int]$PasswordHistory = $DefaultDomainPasswordPolicy.PasswordHistoryCount
ForEach ($user in $users){
Get-ADUserPasswordExpirationDate $user.samaccountname
Write-Verbose "Writing summary event log entry"
$EventLogText = "Finished processing $global:UsersNotified account(s). `n`nFor more information about this script, run Get-Help .\$ScriptName. See the blog post at
http://www.ehloworld.com/318."
$evt.WriteEntry($EventLogText,$infoevent,70)
# $WhatIfPreference = $false
# Remove-ScriptVariables -path $MyInvocation.MyCommand.Name
Remove-ScriptVariables -path $ScriptPathAndNameHi petro_jemes,
Just a little claritification, you need to add the value to the variable "[string]$ou", and also change the language in the variable "$emailbody" in the function "Get-ADUserPasswordExpirationDate".
I hope this helps. -
How can I script out automatic mail profile connection to Exchange 2013
We use a program called Desktop Authority 9.1 that is a fully featured kixstart based logon user profile customization tool. It does a full gamout of things like map drives, folder redirection, import registry edits, run silent application installers,
and of course create the Outlook profile.
There's no issues with this tool creating an outlook profile internally to mail.domain.com, and even detecting laptops and configuring it for outlook anywhere to webm.domain.com and cached mode.
Issue I'm having is trying to roll out Exchange 2013. This tool simply does not seem to create the mail profile. On a test computer I have the hosts file pointed to the new 2013 server from these names: webm, mail, autodiscover. At log
on I simply get an error "The name cannot be resolved. The name cannot be matched to a name in the address list." When you click OK you get a little confusing dialog box with the exchange server name: mail and the mailbox: windows
user ID.
So I tried to do this manually in the Mail (32-bit) control panel applet. It doesnt matter if I put in mail, mail.domain.com, webm, webm.domain.com, email (the netbios name of exchange 2013), etc.. I get the same error. I went into More settings
> Connection > connect to microsoft exchange using HTTP and in the proxy settings I have webm.domain.com, connect SSL Only, only connect to proxy servers that have the name: msstd:webm.domain.com, and the rest is checked and NTLM Authentication is checked.
I simply CANNOT manually create an outlook profile at all. I can surely delete this one, start outlook, click next through the wizard taking all the default options and get Outlook configured that way (via Autodiscover service), but I need a way to
do it manually so I can have Desktop Authority do it manually. Why? Two major reasons:
1. If our end users are greeted with an Outlook startup wizard every time they go to a different computer, and have to click next through it, our help desk is going to be overwhelmed with "what is this outlook startup wizzard?" questions.
2. Desktop Authority also attaches additional mailboxes. We need the outlook profile passed through DA's scripting so different users departmental voice mailboxes are attached in their outlook. IE) Mailbox VM_FAX_Accounting is attached
to all of the accounting associates Outlook.Ok I found another way to get autodiscover to work..
In Group Policy go to User Configuration > Administrative Templates > Microsoft Office 2010 (and 2013 in my case) > Miscellaneous > Suppress recommended settings dialog > Change to ENABLED.
Now go to User Configuration > Administrative Templates > Microsoft Outlook 2010 (and 2013 in my case) > Account Settings > Exchange > Automatically configure profile based on Active Directory Primary SMTP address > Change to ENABLED.
Now for the shared mailboxes, I guess when we plan to migrate a department, their shared mailbox MUST be migrated from 2007 to 2013 on the same evening, and then we must go into that shared mailbox and ensure each individual user has "Full access
permissions" to it.
Now in Desktop Authority we publish this reg file:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Outlook\AutoDiscover\RedirectServers]
"autodiscover-s.outlook.com"=hex(0):
"autodiscover.outlook.com"=hex(0):
"autodiscover.domain.com"=""
[HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Outlook\AutoDiscover\RedirectServers]
"autodiscover-s.outlook.com"=hex(0):
"autodiscover.outlook.com"=hex(0):
"autodiscover.domain.com"=""
[HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Outlook\AutoDiscover\RedirectServers]
"autodiscover-s.outlook.com"=hex(0):
"autodiscover.outlook.com"=hex(0):
"autodiscover.domain.com"=""
Why that? Well it turns out further testing when I added full permission to a new 2013 test shared mailbox, yet another nag screen was presented in Outlook which states "Allow this website to configure [email protected] server settings? autodiscover.domain.com/autodiscover/autodiscover.xml
- Your account was redirected to this website for settings. You should only allow settings from sources you know and trust. (Allow) (Cancel). If end users see this, you can bet our helpdesk calls will be out of control. We undergo security
awareness training and they will question ANYTHING resulting in redirect or dialog boxes asking about trust, and really that's a good thing.
That registry should I think handle Outlook 2007, 2010, 2013, and we will just have to maintain it for future versions.
We maybe have, I dont know less than 5 Outlook 2007 installs and they are on spare laptops, so If I want to cover it all I just have to download the Office 2007 ADMX templates for Group Policy so I can change those two settings above as well.
The other way I thought was to use powershell and script something out to pull from Exchange the GUID, append the @domain.com and put that into a variable that our Desktop Authority application can plug in at startup. But thats a little too much custom
programming whereas I think using GPO's and documented registry keys may be a better fit.
I just have to do testing to figure out what's going to happen to the users profile if it already exists on 2007, then its migrated to 2013. Will it be deleted? Will they lose all of their signatures? I know for many on network
PC's they will be going from direct mapi connection to Cached mode. Is that a good thing? I would imagine less load on the server and network once the mail is downloaded.
We would plan on a slow migration on a departmental basis. Luckily our departments have their own user OU's so applying this group policy can be done in the same manor. -
Problem in script output sending mail
hi ,
I have a problem sending a mail with script output as attachment . I have searched in the forum for the answers but none is solved my question.
I am sending the data to the otf and it is getting the otfdata. but it is not showing the data on the script when it is sent as an attachment to the email , but it is showing only script with null values filled.( means i am getting the mail with attachment but in that attachment there is no data filled in the script send).
the code is like this ..
here i am filling the otfdata and i am exporting the otfdata
CALL FUNCTION 'ZMM_ARRANG_ENTRY_ABR_NATRAB'
EXPORTING
i_nast = nast
i_fonam = tnapr-fonam
i_xscreen = pi_xscreen
i_arc_params = arc_params
i_toa_dara = toa_dara
IMPORTING
e_retcode = px_retcode
EXCEPTIONS
OTHERS = 1.
IF ( sy-subrc <> 0 ). "Fehler
MOVE sy-subrc TO px_retcode.
IF ( pi_xscreen = 'X' ). "Ausgabe auf Bildschirm
MESSAGE ID sy-msgid
TYPE sy-msgty
NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
ELSE.
*---Import OTFDATA from the memory
IMPORT it_otfdata FROM MEMORY ID 'OTF'.
ENDIF.
wa_maildata-obj_name = 'EMAIL'.
wa_maildata-obj_descr = 'Settlement Details'.
*-----mail contents
it_mailtext-line = 'Sub-sequent settlement Details'.
APPEND it_mailtext.
DESCRIBE TABLE it_mailtext LINES v_lines.
READ TABLE it_mailtext INDEX v_lines.
wa_maildata-doc_size = ( v_lines - 1 ) * 255 + STRLEN( it_mailtext ).
*Creation of the entry for the compressed document
CLEAR it_mailpack-transf_bin.
it_mailpack-head_start = 1.
it_mailpack-head_num = 0.
it_mailpack-body_start = 1.
it_mailpack-body_num = v_lines.
it_mailpack-doc_type = 'RAW'.
APPEND it_mailpack.
*-----Get OTF data
LOOP AT it_otfdata.
it_mailcont-line = it_otfdata.
APPEND it_mailcont.
ENDLOOP.
*---Move OTF data into binary table
LOOP AT it_mailcont.
MOVE-CORRESPONDING it_mailcont TO it_mailbin.
APPEND it_mailbin.
ENDLOOP.
*---Get no of lines in Binary data table
DESCRIBE TABLE it_mailbin LINES v_lines.
*---Fill name of the header of email
it_mailhead = 'Subsequent Settlement Details.OTF'.
APPEND it_mailhead.
*---Creation of the entry for the compressed attachment
it_mailpack-transf_bin = 'X'.
it_mailpack-head_start = 1.
it_mailpack-head_num = 1.
it_mailpack-body_start = 1.
it_mailpack-body_num = v_lines.
it_mailpack-doc_type = 'OTF'.
it_mailpack-obj_name = 'EMAIL'.
it_mailpack-obj_descr = 'Settlement Details'.
it_mailpack-doc_size = v_lines * 255.
APPEND it_mailpack.
*----Get email address from the address number of vendor
CALL FUNCTION 'ADDR_GET_REMOTE'
EXPORTING
addrnumber = l_adrnum
TABLES
adsmtp = it_adsmtp.
*----Get mail address
READ TABLE it_adsmtp WITH KEY remark = 'AP_SUB_SETT'.
IF sy-subrc = 0.
it_mailrec-receiver = it_adsmtp-smtp_addr.
it_mailrec-rec_type = 'U'.
it_mailrec-com_type = 'EXT'.
APPEND it_mailrec.
*---Send email with PDF attachment
CALL FUNCTION 'SO_NEW_DOCUMENT_ATT_SEND_API1'
EXPORTING
document_data = wa_maildata
put_in_outbox = 'X'
COMMIT_WORK = 'X'
TABLES
packing_list = it_mailpack
object_header = it_mailhead
contents_bin = it_mailbin
contents_txt = it_mailtext
receivers = it_mailrec.
ELSE.
MESSAGE 'No email id Exist for the vendor' TYPE 'E'.
ENDIF.
please suggest me with your valuable answers .
Regards,
Venkat Appikonda.Hi venkat
Just check if this helps you.
The following part of the code does exactly that.
Selecting details from the spool request table.
SELECT * FROM tsp01 INTO TABLE tb_spool
WHERE rqowner = sy-uname.
IF sy-subrc EQ 0.
SORT tb_spool DESCENDING BY rqcretime.
CLEAR : tb_spool.
READ TABLE tb_spool INDEX 1.
convert spool into PDF format.
CALL FUNCTION 'CONVERT_OTFSPOOLJOB_2_PDF'
EXPORTING
src_spoolid = tb_spool-rqident
TABLES
PDF = tb_lines.
ENDIF.
After this, on execution we get the below mentioned message.
This indicates that a PDF of the SAP Script has been created which is in the format u201C132-long stringsu201D.
In order to send the mail across, the mailing format of the PDF supports u201C255-long stringsu201D. So, the present u201C132-long stringsu201D needs to be converted into u201C255-long stringsu201D. This along with the mail code is mentioned below.
DATA: lv_receiver(50) TYPE c.
REFRESH: tb_obj_txt,
tb_obj_bin,
tb_obj_head,
tb_paklist,
tb_receiver.
CLEAR: tb_obj_txt,
tb_obj_bin,
tb_paklist,
tb_obj_head,
tb_receiver.
CLEAR: tb_adrc.
IF NOT tb_adrc[] IS INITIAL.
Reading the address table with the key as address number.
READ TABLE tb_adrc WITH KEY addrnumber = tb_kna2-adrnr.
IF sy-subrc EQ 0.
Vendor Email ID.
SELECT SINGLE smtp_addr
FROM adr6
INTO wf_mailaddr
WHERE addrnumber = tb_adrc-addrnumber.
IF sy-subrc EQ 0.
Moving the mail address to the receiver itab
MOVE wf_mailaddr TO tb_receiver-receiver.
tb_receiver-rec_type = text-011.
APPEND tb_receiver.
ELSE.
CONCATENATE text-004 tb_kna2-kunnr text-005 INTO lv_receiver
SEPARATED BY space.
If pa_call is initial, the receiver ID is printed; else an INVALID E-mail ID message gets flashed.
IF pa_call IS INITIAL.
WRITE :/ lv_receiver.
ENDIF.
CLEAR: itab.
itab-kunnr = tb_kna2-kunnr.
itab-message = lv_receiver.
APPEND itab.
EXIT. u201CNo mailing for invalid Email id
ENDIF.
ENDIF.
ENDIF.
wf_name = sy-uname.
wf_year = tb_main-bldat(4).
wf_mon = tb_main-bldat+4(2).
*This FM gives the name of the months.
CALL FUNCTION 'MONTH_NAMES_GET'
EXPORTING
language = sy-langu
TABLES
month_names = tb_months.
IF sy-subrc EQ 0.
READ TABLE tb_months WITH KEY mnr = wf_mon.
IF sy-subrc EQ 0.
wf_name = tb_months-ktx.
ENDIF.
ENDIF.
CLEAR: tb_contp.
IF NOT tb_contp[] IS INITIAL.
*Reading the contp itab as per the customer entered on the selection screen.
READ TABLE tb_contp WITH KEY bukrs = pa_bukrs
kunnr = tb_kna2-kunnr.
IF sy-subrc EQ 0.
CONCATENATE text-006 text-008 tb_contp-contp text-008 tb_kna2-kunnr
text-008 wf_name text-008 wf_year INTO wf_sub.
ENDIF.
ELSE.
CONCATENATE text-006 text-008 tb_kna2-kunnr text-008 wf_name
text-008 wf_year INTO wf_sub.
ENDIF.
Subject and Description
CLEAR wa_docdata.
wa_docdata-obj_name = text-007.
wa_docdata-obj_descr = wf_sub.
wa_docdata-obj_langu = sy-langu.
Write main body
tb_obj_txt = text-009.
APPEND tb_obj_txt.
CLEAR tb_obj_txt.
CLEAR tb_paklist.
tb_paklist-head_start = 1.
tb_paklist-head_num = 3.
tb_paklist-body_start = 1.
tb_paklist-body_num = 60.
tb_paklist-doc_type = text-012.
APPEND tb_paklist.
CLEAR tb_paklist.
create PDF file
Transfer the 132-long strings to 255-long strings
LOOP AT tb_lines.
TRANSLATE tb_lines USING ' ~'.
CONCATENATE wf_buffer tb_lines INTO wf_buffer.
ENDLOOP.
TRANSLATE wf_buffer USING '~ '.
DO.
tb_obj_bin = wf_buffer.
APPEND tb_obj_bin.
SHIFT wf_buffer LEFT BY 255 PLACES.
IF wf_buffer IS INITIAL.
EXIT.
ENDIF.
ENDDO.
DESCRIBE TABLE tb_obj_bin LINES lv_lines.
READ TABLE tb_obj_bin INDEX lv_lines.
lv_size = ( lv_lines - 1 ) * 255 + STRLEN( tb_obj_bin ).
Create attachment notification
tb_paklist-transf_bin = co_x.
tb_paklist-head_start = 1.
tb_paklist-head_num = 0.
tb_paklist-body_start = 1.
tb_paklist-body_num = lv_lines.
tb_paklist-doc_type = text-013.
tb_paklist-obj_descr = text-010.
tb_paklist-obj_name = text-010.
tb_paklist-doc_size = lv_size.
APPEND tb_paklist.
*mail the PDF to the receiver.
CALL FUNCTION 'SO_DOCUMENT_SEND_API1'
EXPORTING
document_data = wa_docdata
sender_address = wf_name
sender_address_type = text-014
TABLES
packing_list = tb_paklist
object_header = tb_obj_head
contents_bin = tb_obj_bin
contents_txt = tb_obj_txt
receivers = tb_receiver
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.
CONCATENATE text-003 tb_kna2-kunnr text-005 INTO lv_receiver
SEPARATED BY space.
CLEAR: itab.
itab-kunnr = tb_kna2-kunnr.
itab-message = lv_receiver.
APPEND itab.
IF pa_call IS INITIAL.
WRITE :/ lv_receiver.
ENDIF.
ELSE.
CONCATENATE text-002 tb_kna2-kunnr text-005 INTO lv_receiver
SEPARATED BY space.
CLEAR: itab.
itab-kunnr = tb_kna2-kunnr.
itab-message = lv_receiver.
APPEND itab.
IF pa_call IS INITIAL.
WRITE :/ lv_receiver.
ENDIF.
ENDIF.
Hope this helps.
Harsh -
Powershell script sends e-mail in ISE but not from powershell command line
I have created a script that generates a report of all users who do not have photos in Active Directory. The script runs and sends an e-mail to a distribution list. It runs fine in ISE, but I cannot run it from command line or as a scheduled task. Any suggestions
what I am doing wrong?
#Starts Powershell Snap-In
Start-Transcript -path c:\Scripts\StaffWithoutPhotos.txt
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlyContinue
$mailboxes = $null
$mailboxes = @(Get-Mailbox -OrganizationalUnit "Staff User Accounts" -ResultSize Unlimited | Where {$_.HasPicture -eq $False})
Write-Host $mailboxes
$report = @()
foreach ($mailbox in $mailboxes)
$mbObj = New-Object PSObject
$mbObj | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $mailbox.DisplayName
$report += $mbObj
Write-Host "Diagnostic Output"
Write-Host "Before Mailbox value check"
Write-Host $report
Write-Host "After Mailbox Value check"
if ($mailboxes -ne $null)
Write-Host $report
#Send the report generated to the e-mail list specified above
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "</style>"
#Start-Sleep -Seconds 5
$smtpserver = "MAIL.contoso.com"
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$msg.From = "[email protected]"
$msg.To.Add("[email protected]")
#$msg.To.Add("[email protected]") #Used for testing
$msg.Subject = "Staff without Photos report"
$msg.Body = "This report contains the list of users who do not currently have photos."
$msg.Body += "<p>"
$msg.Body += "After photos are available for these users please submit a request to have their accounts updated or send an e-mail to <a href='mailto:[email protected]?Subject=Staff%20Photo%20Updates' target='_top'> [email protected]
</a> with <b>Staff Photo Updates</b> in the subject."
$msg.Body += "<p>"
$msg.Body += "This report runs on Fridays and will only send a message if we have Staff without Photos. For more information please contact your systems administrator."
$msg.Body += "<p>"
$msg.Body += $Report | ConvertTo-Html -Head $Style
$msg.IsBodyHTML = $true
$smtp.Send($msg)
Stop-TranscriptSo after researching further and not receiving any more replies I decided to rewrite the script and attempt to use the send-mailmessage function. I have been unable to determine the reason for the original not script not working. We use a very similar script
to my original code which works to generate a report and e-mail that report as an attachment and it works without any problems.
After re-writing the script and using the send-mailmessage function I was able to get this report to work as expected. This has now been set up as a scheduled task to run on a server once a week. Here is the final code:
Start-Transcript -path c:\Scripts\StaffWithoutPhotos.txt
#Starts Powershell Snap-In
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010 -erroraction silentlyContinue
$mailboxes = $null
$mailboxes = @(Get-Mailbox -OrganizationalUnit "contoso Staff User Accounts" -ResultSize Unlimited | Where {$_.HasPicture -eq $False})
Write-Host $mailboxes
$report = @()
foreach ($mailbox in $mailboxes)
$mbObj = New-Object PSObject
$mbObj | Add-Member -MemberType NoteProperty -Name "Display Name" -Value $mailbox.DisplayName
$report += $mbObj
Write-Host "Diagnostic Output"
Write-Host "Before Mailbox value check"
Write-Host $report
Write-Host "After Mailbox Value check"
if ($mailboxes -ne $null)
Write-Host $report
#Send the report generated to the e-mail list specified above
$style = "<style>BODY{font-family: Arial; font-size: 10pt;}"
$style = $style + "TABLE{border: 1px solid black; border-collapse: collapse;}"
$style = $style + "TH{border: 1px solid black; background: #dddddd; padding: 5px; }"
$style = $style + "TD{border: 1px solid black; padding: 5px; }"
$style = $style + "</style>"
$smtpserver = "MAIL.contoso.com"
$smtpFrom = "[email protected]"
$smtpTo = "[email protected]"
$messageSubject = "Staff without Photos report"
$Body = "This report contains the list of users who do not currently have photos."
$Body += "<p>"
$Body += "After photos are available for these users please submit a request to the Help Desk to have their accounts updated or send an e-mail to <a href='mailto:[email protected]?Subject=Staff%20Photo%20Updates' target='_top'> [email protected]
</a> with <b><u>Staff Photo Updates</b></u> in the subject."
$Body += "<p>"
$Body += "This report runs on Fridays and will only send a message if we have Staff without Photos. For more information please contact your systems administrator."
$Body += "<p>"
$Body += $Report | ConvertTo-Html -Head $Style
#Send the report
send-mailmessage -from "$smtpFrom" -to "$smtpTo" -subject "$messageSubject" -body "$Body" -smtpServer "$smtpserver" -BodyAsHtml
Stop-Transcript -
Script that enables mail users and kicks out two csv files
I am working on a script that will mainly be used as a scheduled task to enabled mailuser by calling the update-recipient command.
But before it calls that command it will get for various issues that can cause errors.
Missing PrimarySMTP
Display name having a space at front or back.
The external email address being blank.
I have IF statements setup to check for those and then call a function that will save into an array the issue for that user.
Here is the script
<#
.SYNOPSIS
Enable-MailUsers Synced Mail Users in the Exchange environment
THIS CODE IS MADE AVAILABLE AS IS, WITHOUT WARRANTY OF ANY KIND. THE ENTIRE
RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS CODE REMAINS WITH THE USER.
Version .9, 30 June 2014
.DESCRIPTION
This script mail-enables Synced Mail Users and creates a CSV report of mail users that were enabled.
The following is shown:
* Report Generation Time
.PARAMETER SendMail
Send Mail after completion. Set to $True to enable. If enabled, -MailFrom, -MailTo, -MailServer are mandatory
.PARAMETER MailFrom
Email address to send from. Passed directly to Send-MailMessage as -From
.PARAMETER MailTo
Email address to send to. Passed directly to Send-MailMessage as -To
.PARAMETER MailServer
SMTP Mail server to attempt to send through. Passed directly to Send-MailMessage as -SmtpServer
.PARAMETER ScheduleAs
Attempt to schedule the command just executed for 10PM nightly. Specify the username here, schtasks (under the hood) will ask for a password later.
.EXAMPLE
Generate the HTML report
.\Enable-MailUsers.ps1 -SendMail -MailFrom [email protected] -MailTo [email protected] -MailServer ex1.contoso.com -ScheduleAs SvcAccount
#>
param(
[parameter(Position=0,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Send Mail ($True/$False)')][bool]$SendMail=$false,
[parameter(Position=1,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail From')][string]$MailFrom,
[parameter(Position=2,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail To')]$MailTo,
[parameter(Position=3,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Mail Server')][string]$MailServer,
[parameter(Position=4,Mandatory=$false,ValueFromPipeline=$false,HelpMessage='Schedule as user')][string]$ScheduleAs
# Sub Function to neatly update progress
function _UpProg1
param($PercentComplete,$Status,$Stage)
$TotalStages=5
Write-Progress -id 1 -activity "Mail enabled Objects" -status $Status -percentComplete (($PercentComplete/$TotalStages)+(1/$TotalStages*$Stage*100))
#Sub Function create ErrObject output
function _ErrObject{
Param($name,
$errStatus
If(!$err){
Write-Host "error detected"
$script:err = $True
$ErrObject = New-Object -TypeName PSObject
$Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
$Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
$script:ErrOutput += $ErrObject
# 1. Initial Startup
# 1.0 Check Powershell Version
if ((Get-Host).Version.Major -eq 1)
throw "Powershell Version 1 not supported";
# 1.1 Check Exchange Management Shell, attempt to load
if (!(Get-Command Get-ExchangeServer -ErrorAction SilentlyContinue))
if (Test-Path "D:\Exchsrvr\bin\RemoteExchange.ps1")
. 'D:\Exchsrvr\bin\RemoteExchange.ps1'
Connect-ExchangeServer -auto
} elseif (Test-Path "D:\Exchsrvr\bin\Exchange.ps1") {
Add-PSSnapIn Microsoft.Exchange.Management.PowerShell.Admin
.'D:\Exchsrvr\bin\Exchange.ps1'
} else {
throw "Exchange Management Shell cannot be loaded"
# 1.2 Check if -SendMail parameter set and if so check -MailFrom, -MailTo and -MailServer are set
if ($SendMail)
if (!$MailFrom -or !$MailTo -or !$MailServer)
throw "If -SendMail specified, you must also specify -MailFrom, -MailTo and -MailServer"
# 1.3 Check Exchange Management Shell Version
if ((Get-PSSnapin -Name Microsoft.Exchange.Management.PowerShell.Admin -ErrorAction SilentlyContinue))
$E2010 = $false;
if (Get-ExchangeServer | Where {$_.AdminDisplayVersion.Major -gt 14})
Write-Warning "Exchange 2010 or higher detected. You'll get better results if you run this script from an Exchange 2010/2013 management shell"
}else{
$E2010 = $true
$localserver = get-exchangeserver $Env:computername
$localversion = $localserver.admindisplayversion.major
if ($localversion -eq 15) { $E2013 = $true }
#Get date
$filedate = get-date -uformat "%m-%d-%Y"
$filedate = $filedate.ToString().Replace("0", "")
#Get the valid users that are not mail-enabled
_UpProg1 1 "Getting User List" 1
#$Users = Get-mailuser -ResultSize unlimited -OrganizationalUnit "R0018.COLLABORATION.ECS.HP.COM/Accounts/AbbVienet/Users" | ?{$_.legacyexchangeDN -eq ""}
$i = 0
$output = @()
$errOutput = @()
$err = $False
#2 Process users
ForEach ($User in $Users){
$i++
_UpProg1 ($i/$Users.Count*100) "Updating Recipients" 2
If ($user.ExternalEmailAddress -eq $null){
_ErrObject $user.Name, "Missing External Email Address"
ElseIf($user.DisplayName -NotLike "* "){
_ErrObject $user.Name, "DisplayName contains a trailing space"
ElseIf($user.DisplayName -NotLike "_*"){
_ErrObject $user.Name, "DisplayName contains a Leading space"
ElseIf($user.PrimarySmtpAddress -eq $null){
_ErrObject $user.Name, "Missing Primary SMTP address"
Else{
#Disable EmailAddressPolicy on these users
Set-Mailuser $User.Name -EmailAddressPolicyEnabled $false
#pass to Update-recipient
Update-Recipient $User.Name
$LEDN = Get-MailUser $User.Name | Select {$_.LegacyExchangeDN}
If ($LEDN -ne ""){
$object = New-Object -TypeName PSObject
$X500 = "x500:" + $LEDN.'$_.LegacyExchangeDN'
$object | Add-Member -Name 'Name' -MemberType Noteproperty -Value $User.Name
$object | Add-Member -Name 'x500' -MemberType Noteproperty -Value $X500
$output += $object
#Creating CSVFile Output
_UpProg1 99 "Outputting CSV file 3" 3
$CSVFile = "c:\scripts\Mail-enable\Mailenabled_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
If($err){
$ErrCSVFile = "c:\scripts\Mail-enable\ProblemUsers_$((Get-Date).ToString('MM-dd-yyyy_hh-mm-ss')).csv"
$errOutput | Select-Object Name, Comment | ConvertTo-CSV -NoTypeInformation > $ErrCSVFIle
$Output | ConvertTo-Csv -NoTypeInformation > $CSVFile
if ($SendMail)
_UpProg1 95 "Sending mail message.." 4
If($err){
Send-MailMessage -Attachments $CSVFile,$ErrCSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
Else{
Send-MailMessage -Attachments $CSVFile -To $MailTo -From $MailFrom -Subject "Enable Mail Users Script" -BodyAsHtml $Output -SmtpServer $MailServer
if ($ScheduleAs)
_UpProg1 99 "Attempting to Schedule Task.." 4
$dir=(split-path -parent $myinvocation.mycommand.definition)
$params=""
if ($SendMail)
$params+=' -SendMail:$true'
$params+=" -MailFrom:$MailFrom -MailTo:$MailTo -MailServer:$MailServer"
$task = "powershell -c \""pushd $dir; $($myinvocation.mycommand.definition) $params\"""
Write-Output "Attempting to schedule task as $($ScheduleAs)..."
Write-Output "Task to schedule: $($task)"
schtasks /Create /RU $ScheduleAs /RP /SC DAILY /ST 22:00 /TN "Enable Mail Users" /TR $task
The Problem is that when I look at the $errOutput I see things but when I pipe the $erroutput to convertTo-CSV I get this within the CSV file. I think its because I an calling a function to do the updating. But not sure.
Jeff CHi Jeff,
Any updates? If you have any other questions, please feel free to let me know.
A little clarification to the script:
function _ErrObject{
Param($name,
$errStatus
If(!$err){
Write-Host "error detected"
$script:err = $True
$ErrObject = New-Object -TypeName PSObject
$Errobject | Add-Member -Name 'Name' -MemberType Noteproperty -Value $Name
$Errobject | Add-Member -Name 'Comment' -MemberType Noteproperty -Value $errStatus
$script:ErrOutput += $ErrObject
$errOutput = @()
_ErrObject Name, "Missing External Email Address"
$errOutput
_ErrObject Name "Missing External Email Address"
$errOutput
If you have any feedback on our support, please click here.
Best Regards,
Anna Wang
TechNet Community Support -
An apple script that saves mail attachments no longer works in lion
In my mail rules, I have been using an apple script, which, if the sender belongs to a certain group, saves any attached files to a special folder I have for attachments from that group. After installing Lion, It performs other parts of my rule (plays a sound, for instance and moves the mesage to a special mailbox, for another), but it FAILS now to save the attachment using the script below. I hope someone knows of a workaround. If not, I hope apple will fix this soon. Here's the script--
using terms from application "Mail"
on perform mail action with messages theMessages for rule theRule
tell application "Mail"
repeat with oneMessage in theMessages
set {mail attachment:theAttachments} to oneMessage
repeat with oneAttachment in mail attachments of oneMessage
save oneAttachment in ("i828:Users:i8:Desktop:Poker Player:PPlayattach2") & (name of oneAttachment)
end repeat
end repeat
end tell
end perform mail action with messages
end using terms fromThis worked brilliantly!
Thanks
David -
Scripts for setting mail message colors quickly
I've been frustrated at how difficult it is to set the color of a message subject etc in a mailbox. Sometimes applying a color would work, sometimes not, and many clicks required. Finally I wrote a simple script that appears in the Finder's Scripts menu, which applies a particular color to all emails that are selected. I made one version for each color I use (I use these to keep track of emails that are useful references, or that require some action, etc.) I added a leading space to the script names so they would appear at the top of the scripts menu. I wish I could connect them to buttons in the Mail window, but don't know a way to do that, and this is nearly as conveniet.
Here's one of the scripts. Colors can be none, red, orange, blue, gray, green, purple, yellow:
tell application "Mail"
set selectedMessages to selection
set nm to count of selectedMessages
if (nm) is equal to 0 then
display alert "No Messages Selected" message "Select the message(s) you want to color red before running this script."
else
repeat with nn from 1 to nm by 1
set theMessage to item nn of selectedMessages
set the background color of theMessage to red
end repeat
end if
end tellHI Disha
Check out these links. They will surely help
http://www.geocities.com/mpioud/Z_EMAIL_ABAP_REPORT.html
http://www.thespot4sap.com/Articles/SAP_Mail_SO_Object_Send.asp
If you find this answer useful, please reward me for the same.
Good luck
Karthik Potharaju -
Unix script error while mail the pdf file.
Hi all,
I want to do a mail in pdf format via a unix script. for that i used the following query:
# Verplichte variabelen
inputname="dago130r.rdf"
outputname="$DATOUT/dago130rDC.pdf"
mailto="$MAIL_INKOOP_DC"
subject="Opgeloste PV's per Category Manager"
params="p_datum_1='08-08-2006' p_ind_dc_of_rz='D'"
# Opgeloste PV's per Category Manager
# Start script.
# Vanaf hier hoeft in principe niets gewijzigd te worden.
mymail () {
local tmp=$DATTMP/$$.txt
cat "$mailbody" > $tmp 2>/dev/null
do_unix "uuencode $outputname $(basename $outputname) >> $tmp"
check_success
do_unix "mailx -s '$subject' -c '$mailcc' -r '$replyto' '$mailto' < $tmp"
check_success
header
perform "$inputname R DESFORMAT=PDF DESTYPE=FILE DESNAME=$outputname $params"
check_success exit
mymail
footer
exit_check "$total_success"
When i execute this query it will make the pdf file in the output folder as well as in the tmp folder as a text file. but after that it will give me error in the log file as follows.:
09/08/06-11:13:19 [ 25178] -- perform: Successful completion of dago130r.rdf R DESFORMAT=PDF DESTYPE=FILE DESNAME=/appl/tst/ah01/dago/dat/out/dago130rDC.pdf p_datum_1='08-08-2006' p_ind_dc_of_rz='D'
09/08/06-11:13:19 [ 25178] -- do_unix: Successful completion of uuencode /appl/tst/ah01/dago/dat/out/dago130rDC.pdf dago130rDC.pdf >> /appl/tst/ah01/dago/dat/tmp/25178.txt
[ 25178] ,/appl/tst/ah01/dago/dat/tmp/25178.txt,: No such file or directory
[ 25178] "/appl/tst/ah01/dago/home/dead.letter" 1/1
[ 25178]
09/08/06-11:13:19 [ 25178] -- ERROR do_unix: mailx -s 'Opgeloste PV's per Category Manager' -c '' -r '' '[email protected]' < /appl/tst/ah01/dago/dat/tmp/25178.txt returned 1
09/08/06-11:13:19 [ 25178] --
I am not getting why this script not taking the file from the tmp folder and why this error comes??
please help me to go out of this problem.Hi Bhavik,
Please can you tell how you are executing this script. ?
./scritpname or sh scriptname
Can you try the script removing local while declaring the tmp variable ?
naghu
Maybe you are looking for
-
i click s/w update in ipad after few mints its screen turns to black and showing itunes logo..plz suggest wht to do
-
HR payroll extractors : no extractor on CRT table in Business content ?
Hi, your help would be appriciated for the following topics : HR payroll extractors I need a confirmation about the fact that there is no extractor on CRT results (cumulative table) for HR payroll results. By contrast, there is only datasource 0HR_PY
-
Need help in Oracle reports 6i
I have a report in 6i, which displays participant details as output on a single page. Presently page one is printed on a pre-printed format which contains some static text. Now we need to make changes in the report it self to accomodate the static te
-
EJB Session Bean + POJO + JPA ?
Hi all, I have a design consideration regarding the use of ejb's in distributed applications. With older versions of ejb specification one would prefer using ejb's to do both the business logic (session beans) and data access logic (entity) Now with
-
Should a signed applet ever throw a security exception?
hi, I've had a few times when a signed applet seems to throw a security exception (at the moment am trying to figure out a SocketException being thrown). I thought if the applet was signed, and when the browser asks if you want to grant it permission