Гость
Целевая тема:
Создать новую тему:
Автор:
Форумы / Windows [игнор отключен] [закрыт для гостей] / Отправка почты из командной строки.... / 12 сообщений из 12, страница 1 из 1
10.12.2004, 14:52
    #32823382
sanya_tir
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Есть такая проблемка, в моей программе необходимо чтобы автоматически отправлялась почта (файл) на указанный адресс, но так чтобы это письмо оставалось OUTLOOKe. Есть такая утилитка mapisend.exe она прекрасно справляется с этим, если бы не одно но... нормально работает только в Outook Express и в NetSkape, в Outlooke он почему-то адресс берет в кавычки и естественно не отправляет, пока в ручную их не убрать. У пользователей на фирме стоит Outlook. Кто знает подскажите как мне отправлять почту? Вобщем или утилитку подобную надо, чтобы из командной строки отправляла или как-то mapisend с outlook-ом померить....
Спасибо.
...
Рейтинг: 0 / 0
10.12.2004, 15:29
    #32823502
sanya_tir
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
НУ хоть кто-нить подскажет мне????? Очень надо....
...
Рейтинг: 0 / 0
10.12.2004, 15:52
    #32823593
GeT
GeT
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Я так и непонял, нужна программка которая отправляет с командной строки или каким-то образом использую Outlook?
Если через командную строку то я использую программку postie.exe. Например следующим батником можно отправлять
postie -host:адрес_прокси -to:кому -from:откого -nomsg -a:имя_прикрепляемого_файла
Если тебе надо, что бы он оставался еще и в почте у тебя, отправляй поралельно адресату и себе на мыло (будешь получать копию).
...
Рейтинг: 0 / 0
14.12.2004, 11:46
    #32826303
sanya_tir
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Спасибо, но это не совсем то.... на фирме десяток менеджеров, программа - одна, модуль отправки - соответственно тоже один на всех.... и нужно чтобы почта отправлялась именно из почтового ящика, того менеджера, кто запустил отправку почты из программы, т.е. из того почтового клиента, который установлен на машине (по умолчанию), без жесткого указания хоста исходящего почтовика.
...
Рейтинг: 0 / 0
14.12.2004, 12:16
    #32826380
Vw
Vw
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
по простму не захотел тогды вота:
Думаю при желании легко можно переделать на WHS

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
Public Sub SendEmailAtt(ByVal MyTo As String, MySybject As String, _
            Optional MyBody As String, Optional MyAttachment As String)
    
    Dim OutLookApp As Object      'Ссылка на MS Outlook
    Dim OutLookItem As Object     'Ссылка на сообщение
    Dim OlNotRunning As Boolean   'открыт MS Outlook на момент выполнения

On Error Resume Next

'Проверяем не открыт ли уже MS Outlook
Set OutLookApp = GetObject(, "Outlook.Application")

If Err.Number <> 0 Then 'Если ошибка то не открыт и запускаем его
    OlNotRunning = True
    Err.Clear
    Set OutLookApp = CreateObject("Outlook.Application")
End If

'Создание сообщения
Set OutLookItem = OutLookApp.CreateItem(0)
With OutLookItem
    .to = MyTo                'кому
    .Subject = MySybject      'тема
    .Body = MyBody            'текст
    If Dir(MyAttachment) <> "" Then
        .Attachments.Add MyAttachment
    End If
    '.Display Отображение сообщения
    .Send
End With

'Закрытие OutLook если не был запущен до выполнения процедуры отправки
    If OlNotRunning = True Then OutLookApp.Application.Quit
End Sub
p.s. Я тоже постией пользуюсь - класс!
авторсоответственно тоже один на всех.... и нужно чтобы почта отправлялась именно из почтового ящика, того менеджера, кто запустил отправку почты из программы, т.е. из того почтового клиента, который установлен на машине (по умолчанию), без жесткого указания хоста исходящего почтовика.
херь какая-то - постие кажись так тебе и будет отправлять
краткая инфо по postie

For SMTP posting...
postie [-host:server[,...]] -to:address[,...] [-cc:address[,...]] [-bcc:address[,...]]
-from:address [-repltyto:address] -s:subject [-file:filename] [-msg:text] [-nomsg] [-html [-alt]]
[-a:filename ...] [-dir:filespec ...] [-uue] [-user:userid -pass:password] [-url:URL] [-high|-low]
где:
OPTIONS:

-host:hostname - 'hostname' is the name of an SMTP server (or POP3 server),
defaults to 'localhost'. Can also be set in a <FORM> with
a field name of 'postie_host'. When posting mail 'hostname' can
optionally be a comma-separated list of server names to try in
in the order listed.

-port:service - optionally specifiy a port number or service name to connect to.
Can also be set in the config file 'postie.txt' by the:
SMTP, NNTP, POP3 and IMAP4 keywords. You probably will need to
specify this ONLY if you are using a non-standard port or go
through a relay of some sort.

-news - post a newsgroup article (else send mail). Can also be set in a
<FORM> with a field name of 'postie_news'. Also, reverses sense
of '-qp' option (see below).

-imap - read from an IMAP4 server else POP3 is assumed.

-noarchive - when posting to news, set the 'x-no-archive: yes' header so that
DejaNews won't store the article.

-to:address - 'address' is the email address or news-group name of the recipient.
This option can be used multiple times, or a comma separated list
may be used.
NOTE: you can also use addresses of the longer form i.e.
-to:"Andrew Davison <andrew@infradig.com>;" and the older
variant -to:"andrew@infradig.com(Andrew Davison)". Can also be
set in a <FORM> with a field name of 'postie_to'.

-cc:address - 'address' is the email address of the recipient. This option can
be used multiple times, or a comma separated list may be used.
Can also be set in a <FORM> with a field name of 'postie_cc'.

-bcc:address - 'address' is the email address of the recipient. This option can
be used multiple times, or a comma separated list may be used.
NOTE: other recipients will be hidden from each other. Can also be
set in a <FORM> with a field name of 'postie_bcc'.

-tolist:filename - 'filename' is a file with one email address per line, used
for sending to multiple recipients as an alternative to '-to'.
Any line beginning with a '#' is ignored.

-cclist:filename - 'filename' is a file with one email address per line, used
for sending to multiple recipients as an alternative to '-cc'.
Any line beginning with a '#' is ignored.

-bcclist:filename - 'filename' is a file with one email address per line, used
for sending to multiple recipients as an alternative to '-bcc'.
Any line beginning with a '#' is ignored.

-hide - if set other -to: recipients of the message won't see each other. It's
much better to use -bcc: instead.

-high - set importance as high (default is normal).

-low - set importance as low (default is normal).

-dsn - request delivery status notification (from server).

-mdn - request mail disposition notification (from client).

-notify - request delivery & disposition notification (same as -dsn & -mdn).

-receipt - send a receipt to someone who has requested one.

-msgid - generate a Message-ID: header on mail sent (very rare to need this).

-ns - For non-stop sending mode. Don't stop on send errors, try and
deliver to as many recipients as possible. On by default for
list-server processing, otherwise off. If used with '-relay' then
the source message is not deleted when '-rm' used as well.

-from:address - 'address' is the email address of the sender.

-replyto:address - 'address' is the email address to reply to.

-verify - verify email 'from' address (as far as possible).

-s:subject - is a string used for the subject line, e.g. -s:"This is a test"
Can also be set in a <FORM> with a field name of 'postie_subject'.

-file:filename - SMTP: an optional specficiation of an input text-file for the
body of the mail message. If not supplied then standard
input is assumed (terminate with CTRL-D) unless '-msg' or '-nomsg'.

-file:filename - POP3/IMAP4: an optional specification of an output file for the body
of a mail message. If not supplied then standard
output is assumed. If multiple messages are selected
for reading then all output will be concatenated to
the output file (attachments are extracted inline
so this will only work with text messages).

-sep:string - output a string between messages when using -file:filename option.

-raw - use to copy headers as well as body. Turns off -extract option.

-nomsg - SMTP: no message body is sent, just attachments (see above and -a).

-msg:text - SMTP/IMAP4: use as message body. Escape line-breaks using '\r\n'
sequence and '\\' for a \ by itself. If '-file:filename' is used
as well then the file contents are appended to the message text.

-msg:nbr - POP3/IMAP4: select specified message (default is ALL messages).

-first:nbr - POP3/IMAP4: read the next specified number of messages (default is ALL).
Can be specified as 'FIRST n' in config file.

-rm - SMTP: remove file(s) specified by '-file', '-a' & '-url' after use.

-rm - POP3: delete the selected message(s). If -br option is
used then the messages won't be displayed as they are
deleted.

-rm - IMAP4: mark for delete the selected message(s). If -br option is
used then the messages won't be displayed as they are
deleted. There is no method (yet) for undeleting such messages.

-rmlist - SMTP: remove files use in '-tolist:', '-cclist:' or '-bcclist:'.

-rmfile:file - remove specified file after processing.

-purge - IMAP4: any messages marked for deletion are removed from the mailbox (note:
this is permanent).

-html - optionally specifies use of HTML content type (be
sure recipient's mail reader can handle HTML mail
before using). Also make sure a <base> document is
set in the HTML for embedded images and links. In
POP3/IMAP4 mode it formats output to suit display in an
HTML browser (and reverses the sense of any
'multipart/alternative' content type received). Can
also be set in a <FORM> with a field name of 'postie_html'.

-alt - HTML input is also translated to plain-text and both are
sent as MIME multipart/alternative.

-alt:textfile - HTML input is accompanied by specified plain-text and both are
sent as MIME multipart/alternative.

-a:filename - where 'filename' is the name of a file to be sent with the
mail message as a multipart MIME attachment. The file is removed
ONLY if the '-rm' option is also used.
This option can be repeated any number of times.

-i:filename|url - where 'filename' is the name of a file to be included with the
mail message as a related object and 'url' is the URL or CID
of the object as referenced in the message body. All such
included objects are encapsulated and sent with the message. Used
to send HTML mail with images or applets embedded such that they
can be viewed without a web connection.

-url:url - where 'url' is the URL to download and save as a file to possibly
(see -noop option) send as an attachment.
The file is saved to the current-working directory unless the
'-extract:path' option is specified. The file is removed ONLY
if the '-rm' option is also used. Handles redirects automatically.
use the 'PROXY_HOST' and 'PROXY_PORT' config file variables if
you need to use a proxy server (for example for FTP use).
This option can be repeated any number of times.

-url:url|file - where 'url' is the URL whose contents are to be saved to
the file named 'file'. File is automatically added to the
attachment list if sending mail.
This option can be repeated any number of times.

-dir:filespec - all files in named directory are included as attachments.
NOTE: does not recursively search sub-directories. Can be
repeated multiple times and used in conjunction with '-a:'.
Can accept wildcards (see '-pat' option) but note: '*.*'
only matches files WITH an extension, so use '*' to get ALL
files in a directory.

-rdir:filespec - all files in named directory are included as attachments.
NOTE: does recursively search sub-directories. Can be
repeated multiple times and used in conjunction with '-a:'.
Can accept wildcards (see '-pat' option) but note: '*.*'
only matches files WITH an extension, so use '*' to get ALL
files in a directory.

-cnt:number - send message 'number' times (may be useful for testing?).

-binary - force all sent attachments to be binary MIME-type (i.e
'application/octet-stream'). This is useful if attaching
text and/or HTML files so they don't appear in-line in
advanced readers.

-text - text attachments are written in native mode, otherwise they are
written in binary mode.

-inline - mark all attachments as 'inline' for viewing in the message
body rather than as separate attachments.

-use_mime:0|1 - send as a MIME message if set to '1' (on by default).

-qp:0|1 - encode characters as 'quoted printable' content-type
if set to '1' (on by default). Otherwise 8-bit characters
will go thru unchanged with 7-bit encoding (see -8 option). If
'-news' is specified then this option is set to '0' (off by default)

-8 - use 8-bit encoding (allows binary data thru unmodified).
This option is off by default and is not recomended to use except
with 16-bit character sets or when quoted-printable encoding is
not supported. If the server doesn't support RFC1652 then this option
will have no effect.

-user:userid - IMAP4/POP3/NNTP account userid. Can also be set in a <FORM> with
a field name of 'postie_user'.

-pass:passwd - IMAP4/POP3/NNTP account password. Can also be set in a <FORM> with
a field name of 'postie_pass'.

-preauth - used with IMAP4 servers that are 'pre-authorised'. Basically it
reads userid/password but doesn't use them (ie. enter dummy values).

-auth - in CGI mode use HTTP Basic Authentication scheme instead of
user/pass params (this is *slighly* more secure).

-redirect:url - output is an HTTP "Location:" header to redirect browsers.
Used with '-cgi' option only.

-mime:mimetype - sets the output mime-type (default is 'text/html'). Used
with '-cgi' option only, and necessary if used with an
HTML <IMG> tag in conjunction with the '-redirect' option.
You can run multiple POSTIE commands by using <IMG> tags
with harmlessly redirected reponses, or use be daring
and use the <OBJECT> tag to embed text responses.

-cgi:query-string - the command-line is actually an HTTP query-string and text
input is taken from a file in either 'c:\temp' or
'/usr/tmp' depending upon platform. This is for
security reasons so that any arbitrary file cannot
be grabbed. You can change the path using the POSTIE_PATH
environment variable e.g. 'set POSTIE_PATH=c:\uploads'. Any
files specified by '-file:' or '-a:' are taken to be relative to
this path (and '..' is checked for!). See also the
'-post' option.

-post - data input is via CGI POST method rather than a file. Used
with '-cgi' option only.

-import - read an input control stream (see import.txt)

-t - read a Unix sendmail compatible input stream to send mail or news (see -news).
Recognises standard headers.

-every:mins - loop back to start every specified minutes (also 'EVERY mins' config keyword).

-severy:secs - loop back to start every specified seconds (also 'SEVERY secs' config keyword).

-v[:level] - verbose output at designated level (default level is 1 if just '-v').

-q - disables message-sent confirmation and a few others.

-log:filename - appends status info to log file.

-br - list basic POP3/IMAP4 headers only (else message text gets displayed).

-relay[:hostname] - relay mail messages to specified host (default is 'localhost'). Can use the
'-to:address' option with this to force sending to a specific address or
newsgroup (if '-news' used), otherwise the relay host will have to resolve
mailbox addresses. This can be useful when you can't create a .forward file
on the original server but want you mail sent on to you somewhere else. Turns
off '-br' option automatically and turns on '-raw'. See also the
'-rm' and '-ns' options.

-extract[:path] - extract attachments to separate named files, in current-directory or named path.

-get:name - used to retrieve an attachment in CGI mode.

-config - read the 'postie.txt' configuration file (see sample file in this directory).

-listserv:address - set the from/return address on list posts.

-priv - when used with -listserv means that the list is private and only the list owner
can post to the list (i.e. a mailing list), otherwise the list is considered public
(i.e. a discussion list).

-owner:address - declares ownership and address for control messages.

-fetch:path - specifies a path to which file 'fetch' requests are relative to. Oterwise fetch
is diabled. Only list subscribers may issue fetch requests.

-open - if specified then anyone can fetch files (see above), not just subscribers.

-manual - if set list cannot process subscribe/unsubscribe requests.

-noatt - if specified then binary-attachments are dropped.

-uue - attachments OR message are UUencoded before being sent.

-probe:address - test that 'address' is a acceptable to designated host WITHOUT sending any mail. Use (optionally)
DNS Mail Exchanger info to do the lookup on the actual mail host. use the -host option
as well to specifiy a name server (if not 'localhost').

-mx - Send mail directly to a recipients mail server rather than routing locally. Use (optionally) with
-host:name to specify a DNS server to use for Mail eXchanger lookup.

-mime:string - set the MIME type to be used in the Content-Type headers. The default is 'text/plain'
for ordinary messages. Can be set in config file as 'MIME string' as well.

-charset:string - set the character-set to be used in the MIME headers. The default is 'iso-8859-1'
for Western European. Can be set in config file as 'CHARSET string' as well.

-mbox:name - (IMAP4) set the current mailbox (i.e. folder) for reading (default is INBOX).

-create:mbox - (IMAP4) create named mailbox.

-delete:mbox - (IMAP4) delete named mailbox (if no subordinates).

-move:mbox - (IMAP4) move selected message(s) to named mailbox.

-copy:mbox - (IMAP4) copy selected message(s) to named mailbox.

-list:string - (IMAP4) list selective mailboxes. For example '-list:"personal/*"' will list all the folders
under 'personal' (including sub-sub-folders). Use '-list:"personal/%"' to list just the
first sub-level. Use '-list:"%"' to list just the top-level. Of course the delimiter '/' may
be different on your system.

-list - (IMAP4) list all mailboxes (same as '-list:"*"' option).

-masq:string - Used in masquerading. If sender matches string then message is read, otherwise ignored.

-alias:filename - When relaying use file to translate addresses. Each line of the file is of the form
'alias: address' and lines beginning with '#' are ignored. Any address encountered
that matches 'alias' will be translated to 'address'. Can be useful with masquerading.
Address formats will converted where appropriate and comparison is not case-sensistive.
Is also used to provide a conditional read, as any message without an alias match is
ignored (when '-alias' is specified).

-exec:command - on POP3/IMAP4 read, execute 'command' passing message body to standard-input.

-limit:n - send mail to lists in batches of 'n'. gets around RCPT-TO limits on mail servers.

-xit - (POP3/IMAP4) Sets exit code to the number of messages queued for reading (on Windows you
may need to divide by 256).

-etrn:domain - initiate remote SMTP transfer of queued mail (See RFC 1985).

-org:name - the organization name (e.g. -org:"Microsoft Corp.").

-sens:desc - describe the 'sensitivity' of the message (e.g. -sens:"Top Secret (for your eyes only)")

-dh - automatically decode headers with =?charset?q?text?= content.

-meter:filename - write % progress to named file at one second intervals on sends.

-free - frees the console window to run detached (usefull only if you can't shell the program as such).

-pat:pattern - subject must match wild-card pattern to process message (otherwise it is skipped).
-nopat:pattern - subject must not match wild-card pattern to process message (otherwise it is skipped).

( '?' - match exactly one character, '*' - match zero or more )
( '!' - match exactly one alpha, '$' - match zero or more )
( '#' - match exactly one digit, '@' - match zero or more )

For example: postie ... -pat:"*MAKE MONEY FAST*" -rm

-spat:pattern - sender must match wild-card pattern to process message (otherwise it is skipped).
-nospat:pattern - sender must not match wild-card pattern to process message (otherwise it is skipped).

( '?' - match exactly one character, '*' - match zero or more )
( '!' - match exactly one alpha, '$' - match zero or more )
( '#' - match exactly one digit, '@' - match zero or more )

-cert:certfile - use certificate for authentication.

-gmt - format date on sent messages in GMT/UTC rather than local time. This might fix time-zone
and daylight savings problems that some people experience.

-noop - no-operation (also NOOP config keyword).

-unique - extracted file attachments are given a unique name (if they clash) otherwise it just
overwrites a file of the same name (also UNIQUE keyword).

-hdr:string - add a mail header to outgoing messages. For example...

postie -hdr:"X-MyHeader1: blurdy\r\nX-MyHeader2: bloop\r\n" ...

And note: each header must be terminated by CR+LF (as above).

-ldap:hostname - name of an LDAP server to use for directory service lookups (LDAP_HOST in config).

-ldapasdns - use the same host name for the LDAP server as used with DNS lookups (LDAPASDNS in config).

-base:string - LDAP base to use for a search.

-search:pattern - search pattern to look for LDAP lookup (SEARCH in config).

-attrib:name - name of an LDAP attribute to use for email address (the default is 'mail').

-retries:nbr - number of connection retries before giving up (default is zero retries).

-size - display message size.

-sort:key-list - list of keys to sort IMAP messages on (if supported by server). Valid keys are
'arrival', 'date', 'cc', 'reverse', 'size', 'subject' and 'to'. The 'reverse'
keyword changes the sort order of subsequent keys. For example...

postie -imap -sort:"subject reverse date" ...

-search:search-list - list of terms to search IMAP messages on (if SORT supported by server). Valid keys are

postie -imap -sort:"subject reverse date" -search:"since 01-Jan-1999" ...
postie -imap -sort:"subject reverse date" -search:"before 01-Jan-1999" ...
postie -imap -sort:"subject reverse date" -search:"unseen" ...

-search:search-list - list of terms to search IMAP messages on (with SORTing). Valid keys are

postie -imap -search:"since 01-Jan-1999" ...
postie -imap -search:"before 01-Jan-1999" ...
postie -imap -search:"since 01-Jan-1999 before 30-Jun-1999" ...
postie -imap -search:"unseen" ...

-idle - when receiveing via IMAP wait for new messages if none present (only if IDLE extension
is supported by the server).

-header:string - Add prefix string to messages. This can be usefull if message body is being streamed in from a
file or standard input via an external process. For example...

postie -header:"Data follows...\n\n" ...

-ssl - try to enable SSL if the server supports it (old style using special ports).

-tls - try to enable SSL if the server supports it (new style STARTTLS/STLS method).

-mail - input is from a mail file (use -host: to specify the filename).

-decode:base64 - decode a BASE64 input filter.
-decode:uue - decode a UUE input filter. (NOT IMPLEMENTED YET)
-decode:qp - decode a Quoted-Printable input filter. (NOT IMPLEMENTED YET)

-encode:base64 - encode a BASE64 input filter.
-encode:uue - encode a UUE input filter. (NOT IMPLEMENTED YET)
-encode:qp - encode a Quoted-Printable input filter. (NOT IMPLEMENTED YET)

-wrap:n - wrap encodings at this many characters per line. MIME/BASE64
is 72 (DEFAULT), but others may differ.


EXAMPLES:


Decode a BASE64 encoded file...

postie -decode:base64 <base64encoded-file >plain-file


Encode a BASE64 plain file...

postie -encode:base64 -wrap:64 >base64encoded-file <plain-file


Sending mail...

postie -host:mailserver.com -from:fred@here -to:joe@there -s:"Here it is..." -nomsg -a:file.zip
postie -from:fred@here -to:joe@there -to:fred@there -s:"Hello there" <file.txt
postie -from:fred@here -to:joe@there -s:"Hello there" -msg:"This a mail message"
postie -from:fred@here -to:joe@there -s:"Hello there" -html -file:file1.html
postie -from:fred@here -to:"Joe Blow <joe@blow>;" -s:"Hello there" -msg:"This a mail message"
...
Рейтинг: 0 / 0
14.12.2004, 12:26
    #32826398
sanya_tir
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Спасибо.
Пришлите мне плиззз эту утилитку на sanya_tir@mail.ru.
...
Рейтинг: 0 / 0
14.12.2004, 13:16
    #32826552
GeT
GeT
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Отправил
...
Рейтинг: 0 / 0
17.12.2004, 11:10
    #32831808
sanya_tir
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Чет не могу найти в этой утилите, как отправить почту используя почтовый клиент по умолчанию, и именно с того ящика, который там забит для отправки почты по умолчанию.... Если postie позволяет такое, то напишите плизз командную строку для отправки.
...
Рейтинг: 0 / 0
Период между сообщениями больше года.
30.03.2015, 11:21
    #38920847
Ogurezzz
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Привет. Спасибо Vw.
Сделал скрипт на VBS. Создаете файл с расширением .vbs, копируете в него код и запускаете. Он даст краткую справку по пользованию. Есть еще идея "запилить" возможность использования нескольких вложений. Если интересует - сделаю.

Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
Dim objArg
Dim OutLookApp      'Ссылка на MS Outlook
Dim OutLookItem     'Ссылка на сообщение
Dim MyAttachment
set objArg = WScript.Arguments 'Объект, содержит параметры, переданные скрипту.

On Error Resume Next
'Если Outlook закрыт - откроем, если уже открыт - то просто продолжаем работу.
Set OutLookApp = GetObject(, "Outlook.Application")
Set OutLookApp = CreateObject("Outlook.Application")


'Если не введен ни один параметр - выводим краткую справку
if objArg.count = 0 then 
	msgbox("Usage: " & vbCrLf & _
	"./mailer.vbs [Subject] [Mail to. ; - separator] [Body text] [Path to attachment]" )
	WScript.Quit
end if

'Создание сообщения
Set OutLookItem = OutLookApp.CreateItem(0)
With OutLookItem
    if objArg.count > 0 then .Subject = objArg(0)            		'тема
    if objArg.count > 1 then .to = objArg(1)      				'кому
    if objArg.count > 2 then .Body = objArg(2)       			'текст
    if objArg.count > 3 then .Attachments.Add objArg(3)		'вложение
    .Display 'Отображение сообщения
    '.Send	 'Отправка сообщения
End With
...
Рейтинг: 0 / 0
10.04.2015, 08:31
    #38932652
Igor Mitichev
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Ogurezzz,
Удачная штука, спс. Каком методом можно выбрать учетную запись, с которой будет отправляться письмо?
...
Рейтинг: 0 / 0
10.04.2015, 09:41
    #38932722
Igor Mitichev
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Igor Mitichev,
Добавил ключ выбора учетной записи, с которой будет отправляться письмо.
Переделал аргументы на именованные. Может кому пригодится, если в Outlook имеется несколько учетных записей и нужно выбрать e-mail, с которого отправляется сообщение.

Код: vbnet
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
Dim OutLookApp      'Ссылка на MS Outlook
Dim OutLookItem     'Ссылка на сообщение
On Error Resume Next

'Если Outlook закрыт - откроем, если уже открыт - то просто продолжаем работу.
Set OutLookApp = GetObject(, "Outlook.Application")
Set OutLookApp = CreateObject("Outlook.Application")

'Если не введен ни один параметр - выводим краткую справку
if WScript.Arguments.count = 0 then 
	Wscript.Echo("Использование: " & vbCrLf & _
           Wscript.ScriptName & " "  & vbCrLf & _
           "         /Subject:" & Chr(34) & "Тема письма" & Chr(34) & " "  & vbCrLf & _
           "         /MailTo:" & Chr(34) & "Адрес получателя (можно указывать несколько, разделяя их знаком ;" & Chr(34) & " "  & vbCrLf & _ 
           "         /MailFrom:" & Chr(34) & "Адрес отправителя (если в Outlook используется несколько учетных записей, не обязательный параметр)" & Chr(34) & " "  & vbCrLf & _ 
           "         /BodyText:" & Chr(34) & "Текст сообщения" & Chr(34) & " "  & vbCrLf & _ 
           "         /Attach:" & Chr(34) & "Полный путь к прикрепляемому файлу" & Chr(34)  )
	WScript.Quit
end if

Set objNamedArgs = WScript.Arguments.Named
'Создание сообщения
Set OutLookItem = OutLookApp.CreateItem(0)
With OutLookItem
    .Subject = objNamedArgs.Item("Subject")             'тема
    .to = objNamedArgs.Item("MailTo")      		'кому

    If  objNamedArgs.Item("MailFrom") <> "" Then       
    .SentOnBehalfOfName = objNamedArgs.Item("MailFrom") ' обратный адрес
    End If

    .Body = objNamedArgs.Item("BodyText")       	'текст
    .Attachments.Add objNamedArgs.Item("Attach")	'вложение

    .Display 'Отображение сообщения
    .Send	 'Отправка сообщения
End With

...
Рейтинг: 0 / 0
20.12.2015, 14:58
    #39132546
Flatcher
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Отправка почты из командной строки....
Igor Mitichev,
подскажите пожалуйста а как правильно вводить аргументы? Ввожу все а выдает краткую справку причем кракозябрами
...
Рейтинг: 0 / 0
Форумы / Windows [игнор отключен] [закрыт для гостей] / Отправка почты из командной строки.... / 12 сообщений из 12, страница 1 из 1
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]