python实现用户登陆邮件通知的方法,python邮件通知

威尼斯人网上娱乐,python实现用户登陆邮件通知的方法,python邮件通知

本文实例讲述了python实现用户登陆邮件通知的方法。分享给大家供大家参考。具体如下:

这里写在linux计划任务里定时执行,当有新用户登陆时候发送用户名到指定邮箱通知管理员。

#!/usr/bin/env python
#encoding=utf-8
from smtplib import SMTP
import subprocess
smtp = "smtp.qq.com"
user = '1234567'
password = 'xxxx'
run_comd = subprocess.Popen('w¦grep pts',shell=True,stdout=subprocess.PIPE)
data = run_comd.stdout.read()
mailb = ["服务器有新用户登录",data]
mailh = ["From: [email protected]", "To: [email protected]", "Subject: 用户登录监控"]
mailmsg = "\r\n\r\n".join(["\r\n".join(mailh), "\r\n".join(mailb)])
def send_mail():
  send = SMTP(smtp)
  send.login(user,password)
  result = send.sendmail("[email protected]", ("[email protected]",), mailmsg)
  send.quit()
if data == '':
  pass
else:
  send_mail()

希望本文所述对大家的Python程序设计有所帮助。

本文实例讲述了python实现用户登陆邮件通知的方法。分享给大家供大家参考。具体如下:…

下面把主要的代码贴一下:

python实现发送邮件功能,python实现发送邮件

本文实例为大家分享了python实现发送邮件功能的具体代码,供大家参考,具体内容如下

依赖:

Python代码实现发送邮件,使用的模块是smtplib、MIMEText,实现代码之前需要导入包:

import smtplib
from email.mime.text import MIMEText

使用163邮件发送邮件,具体代码实现如下:

import smtplib
from email.mime.text import MIMEText
'''
发送邮件函数,默认使用163smtp
:param mail_host: 邮箱服务器,16邮箱host: smtp.163.com
:param port: 端口号,163邮箱的默认端口是 25
:param username: 邮箱账号 [email protected]
:param passwd: 邮箱密码(不是邮箱的登录密码,是邮箱的授权码)
:param recv: 邮箱接收人地址,多个账号以逗号隔开
:param title: 邮件标题
:param content: 邮件内容
:return:
'''

def send_mail(username, passwd, recv, title, content, mail_host='smtp.163.com', port=25):
  msg = MIMEText(content)  # 邮件内容
  msg['Subject'] = title   # 邮件主题
  msg['From'] = username   # 发送者账号
  msg['To'] = recv      # 接收者账号列表
  smtp = smtplib.SMTP(mail_host, port=port)   # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
  smtp.login(username, passwd)          # 登录发送者的邮箱账号,密码
  # 参数分别是 发送者,接收者,第三个是把上面的发送邮件的 内容变成字符串
  smtp.sendmail(username, recv, msg.as_string())
  smtp.quit() # 发送完毕后退出smtp
  print('email send success.')

if __name__ == '__main__':
  email_user = '[email protected]' # 发送者账号
  email_pwd = 'xxxxx' # 发送者密码,授权码
  maillist = '[email protected]'
  title = '测试邮件标题'
  content = '这里是邮件内容'
  send_mail(email_user, email_pwd, maillist, title, content)

163邮箱的授权码获取方法如下:

  1. 登录163邮箱,点击设置-POP3/SMTP/IMAP,如下:

澳门威尼斯人赌场 1

  1. 开启SMTP服务且可以查询SMTP的host地址:

澳门威尼斯人赌场 2

  1. 点击客户端授权密码,可以重置授权码:

澳门威尼斯人赌场 3

使用QQ邮件发送邮件,具体代码实现如下:

import smtplib
from email.mime.text import MIMEText
'''
发送邮件函数,默认使用163smtp
:param mail_host: 邮箱服务器,qq邮箱host: smtp.qq.com
:param port: 端口号,qq邮箱的默认端口是: 456
:param username: 邮箱账号 [email protected]
:param passwd: 邮箱密码(不是邮箱的登录密码,是邮箱的授权码)
:param recv: 邮箱接收人地址,多个账号以逗号隔开
:param title: 邮件标题
:param content: 邮件内容
:return:
'''
#qq邮箱发送邮件
def send_mail(username, passwd, recv, title, content, mail_host='smtp.qq.com', port=456):
  msg = MIMEText(content)  # 邮件内容
  msg['Subject'] = title   # 邮件主题
  msg['From'] = username   # 发送者账号
  msg['To'] = recv      # 接收者账号列表
  smtp = smtplib.SMTP_SSL(mail_host, port=port)   # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
  smtp.login(username, passwd)          # 登录发送者的邮箱账号,密码
  # 参数分别是 发送者,接收者,第三个是把上面的发送邮件的 内容变成字符串
  smtp.sendmail(username, recv, msg.as_string())
  smtp.quit() # 发送完毕后退出smtp
  print('email send success.')

if __name__ == '__main__':
  email_user = '[email protected]' # 发送者账号
  email_pwd = 'WOSHINIGE123' # 发送者密码,授权码
  maillist = '[email protected]'
  title = '测试邮件标题'
  content = '这里是邮件内容'
  send_mail(email_user, email_pwd, maillist, title, content)

多个 收件人且带附件:

# import smtplib
# from email.mime.text import MIMEText
# '''
# 发送邮件函数,默认使用163smtp
# :param mail_host: 邮箱服务器,qq邮箱host: smtp.163.com
# :param port: 端口号,qq邮箱的默认端口是: 25
# :param username: 邮箱账号 [email protected]
# :param passwd: 邮箱密码(不是邮箱的登录密码,是邮箱的授权码)
# :param recv: 邮箱接收人地址,多个账号以逗号隔开
# :param title: 邮件标题
# :param content: 邮件内容
# :return:
# '''
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

#邮箱服务器地址
email_host = 'smtp.163.com'
#发送者
email_user = '[email protected]'
#授权码
email_pwd = 'WOSHINIGE123'
#多个收件人,使用分号分隔
maillist ='[email protected];[email protected]'
#对多个收件人进行分割,以;为标准,返回结果是list['[email protected]','[email protected]']
email_info = maillist.split(';')
#构造一个发附件的邮件内容对象
new_msg = MIMEMultipart()
#邮件正文内容
new_msg.attach(MIMEText('test email.....'))
#邮件主题
new_msg['Subject'] = 'test email'
#邮件发送者
new_msg['From'] = email_user
#邮件接收者,多个收件人的账号使用,连接,传入类型是str
new_msg['To'] = ','.join(email_info)
#打开a.txt读取文本内容
att = MIMEText(open('a.txt').read())
att["Content-Type"] = 'application/octet-stream'
# 发送附件就得这么写,固定格式,filename指定附件的名字
att["Content-Disposition"] = 'attachment; filename="haha.txt"'
new_msg.attach(att)
# 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
smtp = smtplib.SMTP(email_host, port=25)
# 发送者的邮箱账号,密码,先登录
smtp.login(email_user, email_pwd)
smtp.sendmail(email_user, email_info, new_msg.as_string())
smtp.quit()
print('email send success.')

多个收件人时账号之间使用分号;分割,进行smtp.sendmail(传入的多个收件人类型是list);new_msg[‘TO’]
= recv,接收的类型是str

 使用类实现邮件的发送,即可发送多人也可发送附件:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class SendMail(object):
 def __init__(self, username, passwd, recv, title, content, file=None, email_host='smtp.163.com', port=25):
  self.username = username
  self.passwd = passwd
  self.recv = recv
  self.title = title
  self.content = content
  self.file = file
  self.email_host = email_host
  self.port = port

 def send_mail(self):
  msg = MIMEMultipart()
  #发送内容的对象
  if self.file:#处理附件的
   att = MIMEText(open(self.file, encoding='utf-8').read())
   att["Content-Type"] = 'application/octet-stream'
   att["Content-Disposition"] = 'attachment; filename="%s"'%self.file
   msg.attach(att)
  msg.attach(MIMEText(self.content))#邮件正文的内容
  msg['Subject'] = self.title # 邮件主题
  msg['From'] = self.username # 发送者账号
  #将多个账号'[email protected];[email protected]' 以分号分割,分割为list
  self.recv = self.recv.split(';')
  if isinstance(self.recv, list):
   msg['To'] = ','.join(self.recv)
  else:
   msg['To'] = self.recv # 接收者账号列表
  if self.username.endswith('qq.com'): #如果发送者是qq邮箱
   self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.port)
  else:
   self.smtp = smtplib.SMTP(self.email_host, port=self.port)
  #发送邮件服务器的对象
  self.smtp.login(self.username, self.passwd)
  try:
   self.smtp.sendmail(self.username, self.recv, msg.as_string())
  except Exception as e:
   print('出错了。。', e)
  else:
   print('发送成功!')
  self.smtp.quit()

if __name__ == '__main__':
 m = SendMail(
  username='[email protected]', passwd='xxxxxxx',file='a.txt', recv='[email protected];[email protected]',
  title='多个收件人', content='哈哈哈啊哈哈哈哈', email_host='smtp.163.com', port=25
 )
 m.send_ma

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持帮客之家。

本文实例为大家分享了python实现发送邮件功能的具体代码,供大家参考,具体内容如下
依赖:…

登陆流程图:

Python实现给qq邮箱发送邮件的方法,python发送邮件

本文实例讲述了Python实现给qq邮箱发送邮件的方法。分享给大家供大家参考。具体实现方法如下:

#-*-coding:utf-8-*-  
#========================================== 
# 导入smtplib和MIMEText 
#========================================== 
from email.mime.text import MIMEText 
import smtplib 
#========================================== 
# 要发给谁,这里发给2个人 
#========================================== 
mailto_list=["[email protected]","[email protected]"] 
#========================================== 
# 设置服务器,用户名、口令以及邮箱的后缀 
#========================================== 
mail_host="smtp.qq.com" 
mail_user="naughty610" 
mail_pass="here is your password" 
mail_postfix="qq.com" 
#========================================== 
# 发送邮件 
#========================================== 
def send_mail(to_list,sub,content): 
  ''''' 
  to_list:发给谁 
  sub:主题 
  content:内容 
  send_mail("[email protected]","sub","content") 
  ''' 
  me=mail_user+"<"+mail_user+"@"+mail_postfix+">" 
  msg = MIMEText(content) 
  msg['Subject'] = sub 
  msg['From'] = me 
  msg['To'] = ";".join(to_list) 
  try: 
    s = smtplib.SMTP() 
    s.connect(mail_host) 
    s.login(mail_user,mail_pass) 
    s.sendmail(me, to_list, msg.as_string()) 
    s.close() 
    return True 
  except Exception, e: 
    print str(e) 
    return False 
if __name__ == '__main__': 
  if send_mail(mailto_list,"here is subject","here is content"): 
    print "发送成功" 
  else: 
    print "发送失败"

希望本文所述对大家的Python程序设计有所帮助。

本文实例讲述了Python实现给qq邮箱发送邮件的方法。分享给大家供大家参考。具体实现方…

初始化,定义邮件服务器

澳门威尼斯人赌场 4

self.IMAP_SERVER=’imap.gmail.com’
        self.IMAP_PORT=993
        self.M = None
        self.response
        self.mailboxes = []
登录,选择mailbox:

代码实现:

self.M = imaplib.IMAP4_SSL(self.IMAP_SERVER, self.IMAP_POR
rc, self.response = self.M.login(username, password)
tye,data = m.M.select()
邮件搜索:

#-*- coding=utf-8 -*-
import os,sys,getpass
'''
user.txt 格式
账号 密码 是否锁定 错误次数
jack 123 unlock 0
tom 123 unlock 0
lily 123 unlock 0
hanmeimei 123 unlock 0
lucy 123 unlock 0
'''
# 定义写入文件的函数
def wirte_to_user_file(users,user_file_path):
 user_file = file(user_file_path,'w+')
 for k,v in users.items():
  line = []
  line.append(k)
  line.extend(v)
  user_file.write(' '.join(line)+'\n')
 user_file.close()
# 判断用户文件是否存在,不存在直接退出
user_file_path = 'users.txt'
if os.path.exists(user_file_path):
 user_file = file(user_file_path,'r')
else:
 print 'user file is not exists'
 sys.exit(1)
# 遍历用户文件,将用户包装成字典
users_dic = {}
for user_line in user_file:
 user = user_line.strip().split()
 users_dic[user[0]] = user[1:]
'''
{
 'lucy': ['123', 'unlock', '0'], 
 'lily': ['123', 'unlock', '0'], 
 'jack': ['123', 'unlock', '0'], 
 'hanmeimei': ['123', 'unlock', '0'], 
 'tom': ['123', 'unlock', '0']
}
'''
while True:
 # 输入账号
 input_name = raw_input('please input your username,input "quit" or "q" will be exit : ').strip()
 # 判断是否为退出
 if input_name == 'quit' or input_name == 'q':
  sys.exit(0)
 # 输入密码
 password = getpass.getpass('please input your password:').strip()
 # 判断账号是否存在、是否锁定
 if input_name not in users_dic:
  print 'username or password is not right'
  break

 if users_dic[input_name][1] == 'lock':
  print 'user has been locked'
  break

 # 判断密码是否正确,正确,登陆成功
 if str(password) == users_dic[input_name][0]:
  print 'login success,welcome to study system'
  sys.exit(0)
 else:
  # 如果密码错误则修改密码错误次数
  users_dic[input_name][2] = str(int(users_dic[input_name][2])+1)
  # 密码错误次数大于3的时候则锁定,并修改状态

  if int(users_dic[input_name][2]) >= 3:
   print 'password input wrong has 3 times,user will be locked,please connect administrator'
   users_dic[input_name][1] = 'lock'
   wirte_to_user_file(users_dic,user_file_path)
   break

  wirte_to_user_file(users_dic,user_file_path)

ret, msgnums = m.M.search(None, ‘BODY’, datapath)
获取邮件信息:

以上这篇python实现简单登陆流程的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

status, response = self.M.fetch(id,”(RFC822)”)
mailText = response[0][1]
mail_message = email.message_from_string(mailText)
subject =
unicode(email.Header.make_header(email.Header.decode_header(mail_message[‘subject’])))
#print “subject_________:” +subject
mail_from = email.utils.parseaddr(mail_message[“from”])[1]
mail_to = email.utils.parseaddr(mail_message[“to”])[1]
time = mail_message[‘Date’]
print ‘[‘+mail_message[‘Date’]+’]’+’\n’+’From:’+mail_from+ ‘
To:’+mail_to+’\n’+’Subject:’+subject+’\n’
return self.get_first_text_block(mail_message), subject, mail_from,
time
maintype = email_message_instance.get_content_maintype()
返回邮件里的内容是何种类型,若为text就比较好处理,如果是multipart,还得遍历email_message_instance去根据不同类型处理。

您可能感兴趣的文章:

  • python初学之用户登录的实现过程(实例讲解)
  • Python实现的用户登录系统功能示例
  • Python编写登陆接口的方法

email.message_from_string(mailText)返回了一个结构体,里面包含了邮件的基本信息

邮件里比较蛋疼的是字符串编码的问题,毕竟大家的邮件格式都不一样,有些是unicode,有些是utf-8,有些是gb2312,还有附件,图片等多种格式,

当然这次也只处理了文本,暂时没有需求去处理附件和图片这些。我都是统一将字符转成unicode去处理的。

字符串处理的时候,可以使用chardet判断字符串类型,读写文件的时候可以用codecs指定读写的字符集类型

补充三个例子

Example 1
From project georegistry, under directory georegistry/lib, in source
file smtp.py.
Score: 13
vote
vote
def sendMessage(fromByValue, toByValue, subject, body,
headerByName=None):
    ‘Send a message using SMTP’
    # Prepare
    message = email.message.Message()
    message.add_header(‘from’,
email.utils.formataddr((fromByValue[‘nickname’],
fromByValue[’email’])))
    message.add_header(‘to’,
email.utils.formataddr((toByValue[‘nickname’],
toByValue[’email’])))
    message.add_header(‘subject’, subject)
    message.set_payload(body)
    if headerByName:
        for key, value in headerByName.iteritems():
            message.add_header(key, value)
    # Connect to server
    if fromByValue[‘smtp’] == ‘localhost’:
        server = smtplib.SMTP(‘localhost’)
    else:
        server = smtplib.SMTP_SSL(fromByValue[‘smtp’], 465)
        if len(fromByValue[‘username’]):
            server.login(fromByValue[‘username’],
fromByValue[‘password’])
    # Send mail
    try:
        server.sendmail(fromByValue[’email’], toByValue[’email’],
message.as_string())
    except socket.error, error:
        raise SMTPError(error)
    finally:
        server.quit()

 

Example 2
From project appengine-python3-master, under directory
google/appengine/tools/devappserver2/admin,
in source file
mail_request_handler_test.py.
Score: 10
vote
vote
def test_send(self):
   
self.mox.StubOutWithMock(mail_request_handler.MailRequestHandler,
                             ‘dispatcher’)
    handler = mail_request_handler.MailRequestHandler(None, None)
    handler.dispatcher = self.mox.CreateMock(dispatcher.Dispatcher)
    handler.dispatcher.add_request(
        method=’POST’,
        relative_url=’URL’,
        headers=[(‘Content-Type’, ‘message/rfc822’)],
        body=’mail message’,
        source_ip=’0.1.0.20′)
澳门威尼斯人赌场,    message = self.mox.CreateMock(email.message.Message)
    message.as_string().AndReturn(‘mail message’)
    self.mox.ReplayAll()
    handler._send(‘URL’, message)
    self.mox.VerifyAll()

  

Example 3
From project python-sipsimple-master, under directory
sipsimple/streams/applications, in source file chat.py.
Score: 8
vote
vote
def __str__(self):
        headers = []
        if self.sender:
            headers.append(u’From: %s’ % self.sender)
        for recipient in self.recipients:
            headers.append(u’To: %s’ % recipient)
        for recipient in self.courtesy_recipients:
            headers.append(u’cc: %s’ % recipient)
        if self.subject:
            headers.append(u’Subject: %s’ % self.subject)
        if self.subject is not None:
            for lang, translation in
self.subject.translations.iteritems():
                headers.append(u’Subject:;lang=%s %s’ % (lang,
translation))
        if self.timestamp:
            headers.append(u’DateTime: %s’ % self.timestamp)
        if self.required:
            headers.append(u’Required: %s’ % ‘,’.join(self.required))
        namespaces = {u”: self.standard_namespace}
        for header in self.additional_headers:
            if namespaces.get(header.namespace.prefix, None) !=
header.namespace:
                if header.namespace.prefix:
                    headers.append(u’NS: %s <%s>’ %
(header.namespace.prefix, header.namespace))
                else:
                    headers.append(u’NS: <%s>’ %
header.namespace)
                namespaces[header.namespace.prefix] =
header.namespace
            if header.namespace.prefix:
                headers.append(u’%s.%s: %s’ % (header.namespace.prefix,
header.name, header.value))
            else:
                headers.append(u’%s: %s’ % (header.name,
header.value))
        headers.append(u”)
        headers = ‘\r\n’.join(s.encode(‘cpim-headers’) for s in
headers)

        message = Message()
        message.set_type(self.content_type)
        if isinstance(self.body, unicode):
            message.set_param(‘charset’, ‘utf-8’)
            message.set_payload(self.body.encode(‘utf-8’))
        else:
            message.set_payload(self.body)

        return headers + ‘\r\n’ + message.as_string()

    

Example 4
From project odoo, under directory addons/mail, in source file
mail_thread.py.
Score: 8
vote
vote
def _message_extract_payload(self, message, save_original=False):
        “””Extract body as HTML and attachments from the mail
message”””
        attachments = []
        body = u”
        if save_original:
            attachments.append((‘original_email.eml’,
message.as_string()))
        if not message.is_multipart() or ‘text/’ in
message.get(‘content-type’, ”):
            encoding = message.get_content_charset()
            body = message.get_payload(decode=True)
            body = tools.ustr(body, encoding, errors=’replace’)
            if message.get_content_type() == ‘text/plain’:
                # text/plain -> <pre/>
                body = tools.append_content_to_html(u”, body,
preserve=True)
        else:
            alternative = False
            for part in message.walk():
                if part.get_content_type() ==
‘multipart/alternative’:
                    alternative = True
                if part.get_content_maintype() == ‘multipart’:
                    continue  # skip container
                # part.get_filename returns decoded value if able to
decode, coded otherwise.
                # original get_filename is not able to decode
iso-8859-1 (for instance).
                # therefore, iso encoded attachements are not able to
be decoded properly with get_filename
                # code here partially copy the original get_filename
method, but handle more encoding
                filename=part.get_param(‘filename’, None,
‘content-disposition’)
                if not filename:
                    filename=part.get_param(‘name’, None)
                if filename:
                    if isinstance(filename, tuple):
                        # RFC2231
                       
filename=email.utils.collapse_rfc2231_value(filename).strip()
                    else:
                        filename=decode(filename)
                encoding = part.get_content_charset()  # None if
attachment
                # 1) Explicit Attachments -> attachments
                if filename or part.get(‘content-disposition’,
”).strip().startswith(‘attachment’):
                    attachments.append((filename or ‘attachment’,
part.get_payload(decode=True)))
                    continue
                # 2) text/plain -> <pre/>
                if part.get_content_type() == ‘text/plain’ and (not
alternative or not body):
                    body = tools.append_content_to_html(body,
tools.ustr(part.get_payload(decode=True),
                                                                        
encoding, errors=’replace’), preserve=True)
                # 3) text/html -> raw
                elif part.get_content_type() == ‘text/html’:
                    html = tools.ustr(part.get_payload(decode=True),
encoding, errors=’replace’)
                    if alternative:
                        body = html
                    else:
                        body = tools.append_content_to_html(body,
html, plaintext=False)
                # 4) Anything else -> attachment
                else:
                    attachments.append((filename or ‘attachment’,
part.get_payload(decode=True)))
        return body, attachments

    

Example 5

From project openerp-ktv, under directory openerp/addons/mail, in source
file mail_message.py.
Score: 5

vote
vote
def parse_message(self, message, save_original=False):
        “””Parses a string or email.message.Message representing an
           RFC-2822 email, and returns a generic dict holding the
           message details.

           :param message: the message to parse
           :type message: email.message.Message | string | unicode
           :param bool save_original: whether the returned dict
               should include
an “original“ entry with the base64
               encoded source of the message.
           :rtype: dict
           :return: A dict with the following structure, where each
                    field may not be present if missing in original
                    message::

                    { ‘message-id’: msg_id,
                      ‘subject’: subject,
                      ‘from’: from,
                      ‘to’: to,
                      ‘cc’: cc,
                      ‘headers’ : { ‘X-Mailer’: mailer,
                                    #.. all X- headers…
                                  },
                      ‘subtype’: msg_mime_subtype,
                      ‘body_text’: plaintext_body
                      ‘body_html’: html_body,
                      ‘attachments’: [(‘file1’, ‘bytes’),
                                       (‘file2’, ‘bytes’) }
                       # …
                       ‘original’: source_of_email,
                    }
        “””
        msg_txt = message
        if isinstance(message, str):
            msg_txt = email.message_from_string(message)

        # Warning: message_from_string doesn’t always work correctly
on unicode,
        # we must use utf-8 strings here 🙁
        if isinstance(message, unicode):
            message = message.encode(‘utf-8’)
            msg_txt = email.message_from_string(message)

        message_id = msg_txt.get(‘message-id’, False)
        msg = {}

        if save_original:
            # save original, we need to be able to read the original
email sometimes
            msg[‘original’] = message.as_string() if
isinstance(message, Message) \
                                                  else message
            msg[‘original’] = base64.b64encode(msg[‘original’]) #
binary fields are b64

        if not message_id:
            # Very unusual situation, be we should be fault-tolerant
here
            message_id = time.time()
            msg_txt[‘message-id’] = message_id
            _logger.info(‘Parsing Message without message-id,
generating a random one: %s’, message_id)

        fields = msg_txt.keys()
        msg[‘id’] = message_id
        msg[‘message-id’] = message_id

        if ‘Subject’ in fields:
            msg[‘subject’] = decode(msg_txt.get(‘Subject’))

        if ‘Content-Type’ in fields:
            msg[‘content-type’] = msg_txt.get(‘Content-Type’)

        if ‘From’ in fields:
            msg[‘from’] = decode(msg_txt.get(‘From’) or
msg_txt.get_unixfrom())

        if ‘To’ in fields:
            msg[‘to’] = decode(msg_txt.get(‘To’))

        if ‘Delivered-To’ in fields:
            msg[‘to’] = decode(msg_txt.get(‘Delivered-To’))

        if ‘CC’ in fields:
            msg[‘cc’] = decode(msg_txt.get(‘CC’))

        if ‘Cc’ in fields:
            msg[‘cc’] = decode(msg_txt.get(‘Cc’))

        if ‘Reply-To’ in fields:
            msg[‘reply’] = decode(msg_txt.get(‘Reply-To’))

        if ‘Date’ in fields:
            try:
                date_hdr = decode(msg_txt.get(‘Date’))
                parsed_date = dateutil.parser.parse(date_hdr,
fuzzy=True)
                if parsed_date.utcoffset() is None:
                    # naive datetime, so we arbitrarily decide to make
it
                    # UTC, there’s no better choice. Should not
happen,
                    # as RFC2822 requires timezone offset in Date
headers.
                    stored_date =
parsed_date.replace(tzinfo=pytz.utc)
                else:
                    stored_date = parsed_date.astimezone(pytz.utc)
            except Exception:
                _logger.warning(‘Failed to parse Date header %r in
incoming mail ‘
                                ‘with message-id %r, assuming current
date/time.’,
                                msg_txt.get(‘Date’), message_id)
                stored_date = datetime.datetime.now()
               
            msg[‘date’] = stored_date.strftime(“%Y-%m-%d %H:%M:%S”)

        if ‘Content-Transfer-Encoding’ in fields:
            msg[‘encoding’] =
msg_txt.get(‘Content-Transfer-Encoding’)

        if ‘References’ in fields:
            msg[‘references’] = msg_txt.get(‘References’)

        if ‘In-Reply-To’ in fields:
            msg[‘in-reply-to’] = msg_txt.get(‘In-Reply-To’)

        msg[‘headers’] = {}
        msg[‘subtype’] = ‘plain’
        for item in msg_txt.items():
            if item[0].startswith(‘X-‘):
                msg[‘headers’].update({item[0]: item[1]})
        if not msg_txt.is_multipart() or ‘text/plain’ in
msg.get(‘content-type’, ”):
            encoding = msg_txt.get_content_charset()
            body = tools.ustr(msg_txt.get_payload(decode=True),
encoding, errors=’replace’)
            if ‘text/html’ in msg.get(‘content-type’, ”):
                msg[‘body_html’] =  body
                msg[‘subtype’] = ‘html’
                body = tools.html2plaintext(body)
            msg[‘body_text’] = tools.ustr(body, encoding,
errors=’replace’)

        attachments = []
        if msg_txt.is_multipart() or ‘multipart/alternative’ in
msg.get(‘content-type’, ”):
            body = “”
            if ‘multipart/alternative’ in msg.get(‘content-type’, ”):
                msg[‘subtype’] = ‘alternative’
            else:
                msg[‘subtype’] = ‘mixed’
            for part in msg_txt.walk():
                if part.get_content_maintype() == ‘multipart’:
                    continue

                encoding = part.get_content_charset()
                filename = part.get_filename()
                if part.get_content_maintype()==’text’:
                    content = part.get_payload(decode=True)
                    if filename:
                        attachments.append((filename, content))
                    content = tools.ustr(content, encoding,
errors=’replace’)
                    if part.get_content_subtype() == ‘html’:
                        msg[‘body_html’] = content
                        msg[‘subtype’] = ‘html’ # html version
prevails
                        body =
tools.ustr(tools.html2plaintext(content))
                        body = body.replace(‘ ’, ”)
                    elif part.get_content_subtype() == ‘plain’:
                        body = content
                elif part.get_content_maintype() in (‘application’,
‘image’):
                    if filename :
                       
attachments.append((filename,part.get_payload(decode=True)))
                    else:
                        res = part.get_payload(decode=True)
                        body += tools.ustr(res, encoding,
errors=’replace’)

            msg[‘body_text’] = body
        msg[‘attachments’] = attachments

        # for backwards compatibility:
        msg[‘body’] = msg[‘body_text’]
        msg[‘sub_type’] = msg[‘subtype’] or ‘plain’
        return msg

相关文章