用python调用outlook发邮件的问题

Python09

用python调用outlook发邮件的问题,第1张

我把你的错误信息打印出来。'\xd2\xd1\xd6\xd5\xd6\xb9\xb2\xd9\xd7\xf7'这个意思是“已终止操作”

现在看来是com出了错误。我没有调 过outlook。不过我觉着应该可以成功。因为COM接口的文档少。

你可以先从VBA文档 里学习一下这个接口。再找一些C++调用outlook的例子。

下面是我从网上找的一个例子。仅供参考

#!/usr/bin/env python

"""

A simple address book browser. Descend into the depths of

your Exchange Server through Outlook and find that contacts

list. Then extract those contacts!

NOTE: Generate the type library for Microsoft Outlook first.

Mail Messages

-------------

In MSDN, the interfaces are documented under "Messaging and

Collaboration", "Collaboration Data Objects", "CDO for

Windows 2000", "CDO for Windows 2000", "Messaging",

"Concepts", "CDO Messaging COM Interfaces", "The IMessage

COM Interface", "IMessage Properties".

Unfortunately, not all properties are always available.

Indeed, the 'gen_py' directory inside 'site-packages' may be

a more accurate summary of properties and interfaces.

Saved Items

-----------

    typedef enum {

        olTXT = 0,

        olRTF = 1,

        olTemplate = 2,

        olMSG = 3,

        olDoc = 4,

        olHTML = 5,

        olVCard = 6,

        olVCal = 7

    } OlSaveAsType

Appointment items are saved as vCal by default.

Contact items are saved as vCard by default.

Mail items are saved as text by default.

All other items are saved as text by default.

"""

import win32com.client

import sys, os

# This is needed before we can even talk about different enum values.

outlook = win32com.client.Dispatch("Outlook.Application")

class View:

    "A view onto namespaces."

    def __init__(self, encoding):

        "Initialise the view with a character 'encoding'."

        self.encoding = encoding

class ConsoleView(View):

    "A console-style view."

    show_namespace_property_mapping = {

        win32com.client.constants.olFolder :

            ("+", "Name"),

        win32com.client.constants.olContact :

            (">", "Email1Address"),

        win32com.client.constants.olMail :

            (">", "Subject"),

        None :

            ("?", "Name")

        }

    def __init__(self, encoding, page_width=80, page_limit=20):

        """

        Initialise the view with a character 'encoding' and the optional

        'page_width' and 'page_limit'.

        """

        View.__init__(self, encoding)

        self.page_width = page_width

        self.page_limit = page_limit

    def update_status(self, counter, max_value):

        "Update a status indicator with the given 'counter' value and 'max_value'."

        last_counter = max(counter - 1, 0)

        last_width = int((last_counter * self.page_width) / max_value)

        width = int((counter * self.page_width) / max_value)

        sys.stdout.write("." * (width - last_width))

        if counter == max_value:

            sys.stdout.write("\n")

    def error(self):

        sys.stdout.write("!")

    def show_namespace(self, items):

        "Show the namespace, given a list of 'items'."

        if len(items) > self.page_limit:

            print "!", "Showing the first", self.page_limit, "items only."

        for value in items[:self.page_limit]:

            try:

                decoration, property = self.show_namespace_property_mapping[value.Class]

            except KeyError:

                decoration, property = self.show_namespace_property_mapping[None]

            print decoration, self.get_property(value, property).encode(self.encoding)

    def get_property(self, object, property, default=""):

        try:

            # NOTE: Hack!

            if property == "SentOn":

                return getattr(object, property).Format()

            return getattr(object, property)

        except AttributeError:

            return default

class Extractor:

    "A class used for the extraction of items/objects from folders."

    extract_type_mapping = {

        win32com.client.constants.olAppointment :

            (win32com.client.constants.olVCal, "vcs"),

        win32com.client.constants.olContact :

            (win32com.client.constants.olVCard, "vcf"),

        win32com.client.constants.olMail :

            (win32com.client.constants.olTXT, "txt"),

        None :

            (win32com.client.constants.olTXT, "txt")

        }

    def __init__(self, view=None):

        "Initialise the extractor with the optional 'view'."

        self.view = view

    def extract(self, items, filename):

        "Extract the given 'items' to a file with the given 'filename'."

        total_number = len(items)

        for i in range(0, total_number):

            value = items[i]

            try:

                save_as_type, suffix = self.extract_type_mapping[value.Class]

            except KeyError:

                save_as_type, suffix = self.extract_type_mapping[None]

            try:

                value.SaveAs(os.path.join(filename, str(i) + "." + suffix),

                    save_as_type)

            except AttributeError:

                if self.view:

                    self.view.error()

            except win32com.client.pywintypes.com_error:

                if self.view:

                    self.view.error()

            if self.view:

                self.view.update_status(i + 1, total_number)

class Explorer:

    "A class maintaining the state of exploration."

    def __init__(self, view=None):

        global outlook

        self.current = self.ns = outlook.GetNamespace("MAPI")

        self.view = view

        self._get_namespace()

    def up(self):

        "Ascend into the parent folder returning whether it was possible."

        if self.current != self.ns:

            self.current = self.current.Parent

            self._get_namespace()

            return 1

        return 0

    def down(self, name):

        """

        Descend into the folder with the given 'name' returning whether it

        could be done.

        """

        if self.choices.has_key(name):

            self.current = self.choices[name]

            self._get_namespace()

            return 1

        return 0

    def get_items(self):

        "Return a list of items in the current folder."

        return self.items

    def get_choices(self):

        "Return a dictionary mapping names to objects."

        

        return self.choices

    def _get_namespace(self):

        """

        An internal method which refreshes the current namespace.

        """

        

        self.choices, self.items = get_namespace(self.current, self.view)

def get_namespace(namespace, view=None):

    """

    Get the contents of the given 'namespace', returning a dictionary of

    choices (appropriate for folders) and a list of items (appropriate for

    messages).

    """

    d = {}

    l = []

    # First try looking for folders. Then look for items. And so on.

    for properties in (("Folders", "Name"), ("Items", None)):

        # Look for objects of the current type: folders, items, etc.

        object_name = properties[0]

        try:

            subobject = getattr(namespace, object_name)

        except AttributeError:

            # Ignore the rest of the loop body and start

            # the next iteration.

            continue

        # Index the retrieved items by storing them by name in a dictionary.

        # Cannot slice items, and they always seem to start at index 1.

        total_number = len(subobject)

        for i in range(1, total_number + 1):

            try:

                field_name = properties[1]

                # Store in the dictionary using the specified property, if

                # specified.

                l.append(subobject[i])

                if field_name is not None:

                    d[getattr(subobject[i], field_name)] = subobject[i]

            except AttributeError:

                pass

            # Crude status indicator.

            if view:

                view.update_status(i, total_number)

    return d, l

def main():

    # Get the encoding if specified.

    if len(sys.argv) > 2:

        encoding = sys.argv[2]

    else:

        encoding = "UTF-8"

    view = ConsoleView(encoding)

    explorer = Explorer(view)

    while 1:

        # Prompt the user.

        print "-" * 60

        view.show_namespace(explorer.get_items())

        print "-" * 60

        print "[U]p [D]own [E]xtract [Q]uit [H]elp then <Return>!"

        print "-" * 60

        s = raw_input().strip().upper()[0]

        # Find the right action.        

        if s == "U":

            # Up!

            explorer.up()

        elif s == "D":

            # Prompt for the folder to enter.

            print "Down into:"

            name = raw_input()

            if not explorer.down(name):

                print "No such object."

                

        elif s == "E":

            # Prompt for the file to extract to.

            print "Extract to:"

            filename = raw_input()

            print "Extracting..."

            extractor = Extractor(view)

            extractor.extract(explorer.get_items(), filename)

            

        elif s == "Q":

            print "Exiting..."

            raise SystemExit

        elif s == "H":

            print "Type the D key then <Return> to enter a folder."

            print "Give the exact folder name when prompted and press <Return>."

            print "Type the U key then <Return> to move up one level."

            print "Type the Q key then <Return> to quit."

            print "Type the H key then <Return> to read this again."

            print "Type the E key then <Return> to extract items."

            print "Give a filename when prompted and press <Return>."

            print

            print "Good luck!"

        else:

            print "No such command."

if __name__ == "__main__":

    main()

# vim: tabstop=4 expandtab shiftwidth=4

想用python做一个很简单的接收邮件的功能,只看python的官方doc(http://docs.python.org/2/library/imaplib.html)真的很不好懂,经过google之,探索之,稍微总结一下:

要使用imap接收邮件,当然要导入imaplib拉.

import imaplib

然后按常规的,建立链接→登录

conn = imaplib.IMAP4("imap.xxx.com",143)

conn.login("userName","password")

然后我想查看收件箱的邮件,咋办呢?要先选择一个目录,收件箱默认名称是"INBOX",IMAP是支持创建文件夹,查看其它文件夹的,如果是自己新建的文件夹,那么名称一般会是"INBOX.新建文件夹",不同的邮箱可能表示方式不一样,如果你不知道的话,那运行conn.list()查看所有的文件夹.

conn.select("INBOX")

选择后,然后查看文件夹,注意,IMAP的查看其实是一个搜索的过程,IMAP的原始命令是search all(大概的),在python里这么用:

type, data = conn.search(None, 'ALL')

然后返回的是这个收件箱里所有邮件的编号,按接收时间升序排列,最后的表示最近.

search这个很鬼麻烦,因为官方文档里没讲这个函数的第二个参数怎么用,于是找了下,可以填的命令有:

http://www.afterlogic.com/mailbee-net/docs/MailBee.ImapMail.Imap.Search_overload_1.html

于是如果我想找Essh邮件的话,使用

type, data = conn.search(None, '(SUBJECT "Essh")')

里面要用一个括号,代表是一个查询条件,可以同时指定多个查询条件,例如FROM xxxx SUBJECT "aaa",注意,命令要用括号罩住(痛苦的尝试)

search第一个参数是charset的意思,填None表示用默认ASCII,

data里获取到的是一个只有一个字符串元素的数组,包含很多数字,用空格隔开

['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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103'

于是想获取最后一封的做法是:

msgList = data[0].split()

last = msgList[len(msgList) - 1]

然后把那个邮件获取回来,用fetch函数

例子:

conn.fetch(last, '(RFC822.SIZE BODY[HEADER.FIELDS (SUBJECT)])')

但是返回的是一串MIME编码的东东,看不懂,如果能像eml那一操作一封邮件就好了.

方法是有的,用email库.

import email

然后以RFC822获取邮件格式,再用email.message_from_string转换为message对象.就可以当message操作了,(http://docs.python.org/2/library/email.message.html)

type,data=connect.fetch(msgList[len(msgList)-1],'(RFC822)')

msg=email.message_from_string(data[0][1])

content=msg.get_payload(decode=True)

最后content得到就是邮件的内容了

木马病毒,

作用与短消息SMS的用Python编写的木马程序!

这个病毒主体文件是个 Python 脚本,只能在支持 Python 的手机平台上运行。

这个脚本文件是嵌在一个 SIS 安装包中的。SIS 安装程序伪装成 “Icq_Python” 诱骗用户安装,并和正常程序一样,安装后程序图标会出现在菜单栏中,并生成如下文件:

!:\system\apps\Icq_reggerNEW\Icq_reggerNEW.app

!:\system\apps\Icq_reggerNEW\default.py

!:\system\apps\Icq_reggerNEW\Icq_reggerNEW.rsc

!:\system\libs\keypress.pyd

!:\system\libs\inbox.pyd

!:\system\libs\appswitch.pyd

其中三个 pyd 文件是病毒脚本用到的导入模块。

当用户点击程序图标运行时,病毒脚本文件 default.py 就会被执行,其行为如下:

a)持续向一个指定号码发送短信;

b)删除收件箱中来自此指定号码的回复短信;

这样用户的手机费就在毫无察觉的情况下被骗取,号码对应的服务商就可以从中牟取暴利。马上查了下话费,没事!