コード例 #1
0
ファイル: main.py プロジェクト: OneirdyniaYi/AutoFgo
    def send_mail(self, status):
        # status: 'err' or 'done'
        self.grab((0, 0, 1, 1), 'final_shot')
        with open(ROOT + 'data/fgo.LOG', 'r') as f:
            res = f.readlines()
            res = [x.replace('<', '&lt;').replace('>', '&gt;') for x in res]
            res = ''.join([x[:-1] + '<br />' for x in res])
        msg = MIMEMultipart()
        with open(ROOT + 'data/final_shot.png', 'rb') as f:
            mime = MIMEBase('image', 'jpg', filename='shot.png')
            mime.add_header('Content-Disposition',
                            'attachment', filename='shot.png')
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            mime.set_payload(f.read())
            encoders.encode_base64(mime)
            msg.attach(mime)

        msg.attach(MIMEText('<html><body><p><img src="cid:0"></p>' +
                            '<font size=\"1\">{}</font>'.format(res) +
                            '</body></html>', 'html', 'utf-8'))
        msg['From'] = Header('why酱のFGO脚本', 'utf-8')
        msg['Subject'] = Header(
            '[FGO] - Status: {}, {}'.format(status, time.strftime('%m-%d%H:%M')), 'utf-8')
        server = smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT)
        try:
            server.ehlo()
            # server.starttls()
            server.login(FROM_ADDRESS, PASSWD)
            server.sendmail(FROM_ADDRESS, [TO_ADDRESS], msg.as_string())
            server.quit()
            print('➜ Mail sent successfully. Please check it.')
        except Exception as e:
            print('\nError type: ', e)
            print('➜ Mail sent failed. Maybe there are something wrong.')
コード例 #2
0
    def send_email_file(self,
                        to_addrs,
                        msg_text,
                        file_path,
                        subject_test='来自SMTP的问候'):
        # 邮件对象
        msg = MIMEMultipart('alternative')
        # 邮件正文是MIMEText:
        msg.attach(MIMEText(msg_text, 'plain', 'utf-8'))

        with open(file_path, 'rb') as f:
            # 设置附件和MIME,从本地读取一个图片
            mime = MIMEBase('image', 'jpeg', filename=file_path.split('/')[-1])
            # 加上必要的头信息:
            mime.add_header('Content-Disposition',
                            'attachment',
                            filename=file_path.split('/')[-1])
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMultipart:
            msg.attach(mime)
        return self.send_email_base(to_addrs, msg, subject_test)
コード例 #3
0
ファイル: messenger.py プロジェクト: hyice/townshipper
def send_mail(subject, content, image=None):
    server = _smtp_server()

    if not server:
        return False

    msg = MIMEMultipart()
    msg['From'] = formataddr((Header('Auto Shipper',
                                     'utf8').encode(), _from_email))
    msg['Subject'] = Header(subject, 'utf8').encode()

    if image:
        image.thumbnail((1000, 1000))
        image.save('tmp/thumbnail.png')
        with open('tmp/thumbnail.png', 'rb') as file:
            msg_image = MIMEBase('image', 'png', filename='attachment.png')
            msg_image.add_header('Content-Disposition',
                                 'attachment',
                                 filename='attachment.png')
            msg_image.add_header('Content-ID', '<0>')
            msg_image.add_header('X-Attachment-Id', '0')

            msg_image.set_payload(file.read())

            encoders.encode_base64(msg_image)

            msg.attach(msg_image)

            content += '<p><img src="cid:0"></p>'

    msg.attach(MIMEText(content, 'html', 'utf8'))

    server.sendmail(_from_email, _to_email, msg.as_string())
    server.quit()
    return True
コード例 #4
0
ファイル: pygmail.py プロジェクト: jinurhee/scripts
    def send_msg(self, to, subject, body, attachments = None):
        if attachments:
            msg = MIMEMultipart()
            msg.attach(MIMEText( body))
        else:
            msg = MIMEText(body)
        msg['To']      = to
        msg['From']    = self.__username
        msg['Subject'] = subject
        if attachments:
            for path in attachments:
                if not os.path.exists(path):
                    break
 
                content_type, encoding = mimetypes.guess_type(path)
                if content_type is None or encoding is not None:
                    content_type = 'application/octet-stream'
 
                main_type, subtype = content_type.split('/', 1)
 
                with open(path, 'rb') as file:
                    data = file.read()
                    attachment = MIMEBase(main_type, subtype)
                    attachment.set_payload(data)
                    email.encoders.encode_base64(attachment)
 
                attachment.add_header('Content-Disposition', 'attachment',
                                       filename = os.path.basename(path))
                msg.attach(attachment)
 
        status = self.smtp.sendmail(self.__username, to, msg.as_string())
        return status
コード例 #5
0
    def mysendmail(self, send_file=False, test_type='plain'):
        # 配置邮件正文
        if send_file:
            self.msg = MIMEMultipart()
            with open('', 'rb') as f:
                mime = MIMEBase('image', 'png', filename=self.file_name)
                mime.add_header('Content-Disposition',
                                'attachment',
                                filename='test.png')
                mime.add_header('Content-ID', '<0>')
                mime.add_header('X-Attachment-Id', '0')
                mime.set_payload(f.read())
                encoders.encode_base64(mime)
                self.msg.attach(mime)
        else:
            self.msg = MIMEText(self.message, test_type, 'utf-8')
        # 配置邮件发送这及显示名称
        self.msg['From'] = self._format_addr(u'%s <%s>' %
                                             (self.from_name, self.from_addr))
        # 配置邮件接受这及显示名称
        # msg['To']接受的是字符串而不是list,如果有多个邮件地址,用,分隔即可
        self.msg['To'] = self._format_addr(u'%s <%s>' %
                                           (self.to_name, self.to_addr))
        # 配置邮件主题
        self.msg['Subject'] = Header(u'%s' % self.subject, 'utf-8').encode()

        # 发送电子邮件
        self.server = smtplib.SMTP()
        self.server.connect(self.smtp_server, 25)
        self.server.login(self.from_addr, self.mail_pass)
        self.server.sendmail(self.from_addr, [self.to_addr],
                             self.msg.as_string())
        self.server.quit()
コード例 #6
0
ファイル: smtp.py プロジェクト: yastrov/py-tips
def newMail(mail_from, mail_to, mail_subj, mail_text, attach_list=[], mail_coding='utf-8'):
    """формирование сообщения"""
    multi_msg = MIMEMultipart()
    multi_msg['From'] = Header(mail_from, mail_coding)
    multi_msg['To'] = Header(mail_to, mail_coding)
    multi_msg['Subject'] =  Header(mail_subj, mail_coding)

    msg = MIMEText(mail_text.encode('utf-8'), 'plain', mail_coding)
    msg.set_charset(mail_coding)
    multi_msg.attach(msg)

    # присоединяем атач-файл
    for _file in attach_list:
        if exists(_file) and isfile(_file):
            with open(_file, 'rb') as fl:
                attachment = MIMEBase('application', "octet-stream")
                attachment.set_payload(fl.read())
                email.encoders.encode_base64(attachment)
                only_name_attach = Header(basename(_file), mail_coding)
                attachment.add_header('Content-Disposition',\
                    'attachment; filename="%s"' % only_name_attach)
                multi_msg.attach(attachment)
        else:
            if(attach_file.lstrip() != ""):
                print("Файл для атача не найден - %s" %_file)
    return multi_msg
コード例 #7
0
ファイル: 发邮件.py プロジェクト: qlong8807/python3-lesson
def get_attach_msg(from_addr, to_addr):
    # 邮件对象:
    msg = MIMEMultipart()
    msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
    msg['To'] = _format_addr('管理员 <%s>' % to_addr)
    msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

    # 邮件正文是MIMEText。文本plain和网页HTML可以同时存在。
    msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))  #这个是带附件的text邮件
    # msg.attach(MIMEText('<html><body><h1>Hello</h1>' +
    #                     '<p><img src="cid:0"></p>' +
    #                     '</body></html>', 'html', 'utf-8'))#这个是带附件的HTML邮件,可以把附件的图片放到邮件正文中。

    # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
    with open('/Users/apple/Pictures/111.png', 'rb') as f:
        # 设置附件的MIME和文件名,这里是png类型:
        mime = MIMEBase('image', 'png', filename='test.png')
        # 加上必要的头信息:
        mime.add_header('Content-Disposition',
                        'attachment',
                        filename='test.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)
        return msg
コード例 #8
0
ファイル: mon.py プロジェクト: dookim/URQA-MessageBroker
def send_mail(from_user, pwd, to_user, cc_users, subject, text, attach):
        COMMASPACE = ", "
        msg = MIMEMultipart("alternative")
        #msg =  MIMEMultipart()
        msg["From"] = from_user
        msg["To"]   = to_user
        msg["Cc"] = COMMASPACE.join(cc_users)
        msg["Subject"] = Header(s=subject, charset="utf-8")
        msg["Date"] = Utils.formatdate(localtime = 1)
        msg.attach(MIMEText(text, "html", _charset="utf-8"))

        if (attach != None):
                part = MIMEBase("application", "octet-stream")
                part.set_payload(open(attach, "rb").read())
                Encoders.encode_base64(part)
                part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach))
                msg.attach(part)

        smtp_server  = "smtp.gmail.com"
        port         = 587

        smtp = smtplib.SMTP(smtp_server, port)
        smtp.starttls()
        smtp.login(from_user, pwd)
        print "gmail login OK!"
        smtp.sendmail(from_user, cc_users, msg.as_string())
        print "mail Send OK!"
        smtp.close()
コード例 #9
0
ファイル: SendMail.py プロジェクト: kuku940/python3-webapp
def sendMsgWithImage(from_addr, to_addr):
    """
    发送正文带有图片的邮件
    :return:
    """
    msg = MIMEMultipart()
    msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
    msg['To'] = _format_addr('管理员 <%s>' % to_addr)
    msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

    # 邮件正文是MIMEText:
    msg.attach(
        MIMEText(
            '<html><body><h1>Hello</h1>' + '<p><img src="cid:0"></p>' +
            '</body></html>', 'html', 'utf-8'))

    # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
    with open('../../../static/images/heben.jpg', 'rb') as f:
        # 设置附件的MIME和文件名,这里是png类型:
        mime = MIMEBase('image', 'png', filename='heben.jpg')
        # 加上必要的头信息:
        mime.add_header('Content-Disposition',
                        'attachment',
                        filename='test.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

    return msg
コード例 #10
0
    def send_mail_with_attach(self, from_addr, to_addr, subject, content):
        # 邮件对象:
        msg = MIMEMultipart()
        from_addr = 'Python爱好者<%s>' % from_addr
        to_addr = '管理员<%s>' % to_addr
        msg['From'] = self._format_addr('Python爱好者<*****@*****.**>')
        msg['To'] = self._format_addr(to_addr)
        msg['Subject'] = Header(subject, 'utf-8').encode()

        # 邮件正文是MIMEText:
        msg.attach(MIMEText(content, 'plain', 'utf-8'))

        # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
        with open('/home/wfq/ops/static/image/qicheng.jpg', 'rb') as f:
            # 设置附件的MIME和文件名,这里是png类型:
            mime = MIMEBase('image', 'jpg', filename='qicheng.jpg')
            # 加上必要的头信息:
            mime.add_header('Content-Disposition',
                            'attachment',
                            filename='qicheng.jpg')
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMultipart:
            msg.attach(mime)
            server = self._get_smtp_server()
            server.sendmail(from_addr, [to_addr], msg.as_string())
            server.quit()
        return ''
コード例 #11
0
def send_mail(test_module):
    from_addr = CONFIG['FROM']
    password = CONFIG['PASSWORD']
    smtp_server = CONFIG['SMTP']
    to_addr = CONFIG['TO']

    # Email object
    msg = MIMEMultipart()
    msg['From'] = _format_add(u"OSPerformance<%s>" % from_addr)
    msg['To'] = _format_add(u"Tester<%s>" % to_addr)
    msg['Subject'] = Header(u"OSPerformance test finish... %s" % test_module,
                            "utf-8").encode()
    # Email body
    msg.attach(
        MIMEText(test_module +
                 ' Test finished. \nResult please refer to the attachment'))
    # Email attachment
    with open('E:/Automation/square-compat.xml', 'rb') as f:
        mime = MIMEBase('xml', 'xml', filename='test.xml')
        mime.add_header('Content-Disposition',
                        'attachment',
                        filename='test.xml')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-ID', '0')
        mime.set_payload(f.read())
        encoders.encode_base64(mime)
        msg.attach(mime)

    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()
コード例 #12
0
ファイル: send-attachment.py プロジェクト: mass10/python.note
def _send(subject, mail_from, rcpt_to, body, filename):

	root_message = MIMEMultipart()
	root_message["Subject"] = smtplib.email.Header.Header(subject, "utf-8")
	root_message["From"] = mail_from
	root_message["To"] = rcpt_to
	root_message["Date"] = formatdate()

	# 本文
	message = MIMEText(body)
	message.add_header("Content-Type", "text/plain; charset=UTF-8")
	root_message.attach(message)

	# 添付ファイル
	attachment = MIMEBase("text", "")
	attachment_body = _read_text_file(filename)
	attachment.set_payload(attachment_body)
	encoders.encode_base64(attachment)
	attachment.add_header("Content-Disposition", "attachment", filename=filename)
	root_message.attach(attachment)

	s = smtplib.SMTP("127.0.0.1:25")
	composed = root_message.as_string()
	s.sendmail(mail_from, [rcpt_to], composed)

	s.close()
コード例 #13
0
def multipart_format(parts):
    """Make a multipart message

    Args:
        parts: list of (content_type, data) tuples

    Returns:
        (headers, data) tuple
    """
    multi_message = MIMEMultipart('related')
    for content_type, data in parts:
        msg = MIMEBase(*content_type.split('/', 1))
        msg.set_payload(data)
        multi_message.attach(msg)

    body_lines = []
    in_headers = True
    last_key = None
    headers = {}
    for line in multi_message.as_string().splitlines(True):
        if in_headers:
            if line == '\n':
                in_headers = False
            elif line.startswith(' ') and last_key:
                headers[last_key] += line.rstrip()
            else:
                key, value = line[:-1].split(':')
                headers[key] = value.strip()
                last_key = key
        else:
            body_lines.append(line)
    return headers, ''.join(body_lines)
コード例 #14
0
ファイル: Autotest.py プロジェクト: hufengping/percolata
def mail(mail_to, subject, text, file):
    """send email"""

    mailserver = smtplib.SMTP("smtp.gmail.com", 587)
    mailserver.starttls()
    mailserver.ehlo()
    mailserver.login(cred.get('GMAIL','USER'), cred['GMAIL']['PASSWD'])

    msg = MIMEMultipart()
    text_msg = MIMEText(text, "html")
    msg.attach(text_msg)
    contype = 'application/octet-stream'
    maintype, subtype = contype.split('/', 1)
    data = open(file, 'rb')
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read())
    data.close()
    email.Encoders.encode_base64(file_msg)
    basename = os.path.basename(file)
    file_msg.add_header('Content-Disposition', 'attachment', filename=basename)
    msg.attach(file_msg)

    msg['Date'] = email.Utils.formatdate()
    msg['From'] = "*****@*****.**"
    msg['Subject'] = subject

    mailserver.sendmail(cred.get('GMAIL', 'USER'), mail_to, msg.as_string())
    mailserver.close()
コード例 #15
0
def send_email(from_addr, pwd, to_addr, subject, pics_path):

    msg = MIMEMultipart()
    msg['From'] = _format_addr('<%s>' % from_addr)
    msg['To'] = _format_addr('<%s>' % to_addr)
    msg['Subject'] = Header(subject, 'utf-8').encode()
    msg.attach(MIMEText('Text', 'plain', 'utf-8'))
    for pic in pics_path:
        pic_name = pic.split('/')[1]
        print("Adding %s to attachment" % pic_name)
        with open(pic, 'rb') as f:
            mime = MIMEBase('image', 'png', filename=pic_name)
            mime.add_header('Content-Disposition', 'attachment', filename=pic_name)
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            mime.set_payload(f.read())
            encoders.encode_base64(mime)
            msg.attach(mime)

    smtp_server = 'owa.zingsemi.com'

    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.login(from_addr, pwd)
    server.sendmail(from_addr, [to_addr], msg)
    server.quit()
コード例 #16
0
    def smtp(self):
        server = smtplib.SMTP_SSL(smtpServer, smtpServer_host)
        server.set_debuglevel(1)
        server.login(address, password)
        content = """
                执行测试中....
                测试已完成!!!
                生成报告中....
                报告已生成....
                报告已邮件发送!!!
                """
        msg = MIMEMultipart()
        msg["From"] = self.__format__addr("%s" % address)
        msg["To"] = self.__format__addr("%s" % toAddress)
        msg["Subject"] = Header("测试报告", "utf-8").encode()

        msg.attach(MIMEText(content, "plain", "utf-8"))

        with open(mail_path, "rb") as f:
            mime = MIMEBase("file", "html", filename="test.html")
            mime.add_header("Content-Disposition", "attachment", filename="test.html")
            mime.add_header("Content-ID", "<0>")
            mime.add_header("X-Attachment-Id", "0")
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMultipart:
            msg.attach(mime)
        server.sendmail(address, [toAddress], msg.as_string())
        server.quit()
コード例 #17
0
    def send_mail(self, to, subject, body, attachments=[], full_attachments={}):
        '''Sends a message to the given recipient, attachments
        is a list of file paths to attach, they will be attached with 
        the given names, and if there is a problem they won't be 
        attached and the message will still be sent.
        
        PARAMATERS:
        to - Email address to send the message to. (String)
        subject - Subject of the email (String)
        body - Body of the email (html allowed) (String)
        attachments - A list of attachments to the message.
        full_attachments - A dict of things to attach, name => data.
                           each name should be unique.
        
        Raises a NotConfiguredException if smtp has not yet been set
        up.
        '''
        
        if not self._smtp_configured:
            raise NotConfiguredException, "SMTP is not configured."
        
        # Setup the message
        msg = MIMEMultipart()
        msg['From'] = self.smtp_username
        msg['To'] = to
        msg['Subject'] = subject

        # Attach the body.
        msg.attach(MIMEText(body, 'html'))

        # Attach each attachment.
        for attach in attachments:
            with open(attach, 'rb') as o:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(o.read())
                encoders.encode_base64(part)
                part.add_header('Content-Disposition',
                       'attachment; filename="%s"' % os.path.basename(attach))
                msg.attach(part)
                
        # Attach everything from the full attachments dictionary.
        for name in full_attachments.keys():
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(full_attachments[name])
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % (name))
            msg.attach(part)

        # Beam me up Scotty!
        mailServer = smtplib.SMTP(self.smtp_url, self.smtp_port)
        mailServer.ehlo()
        mailServer.starttls()
        mailServer.ehlo()
        mailServer.login(self.smtp_username, self.smtp_password)
        mailServer.sendmail(self.smtp_username, to, msg.as_string())
        mailServer.close()

        if DEBUG:
            print ("%s - Message sent to: %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), to))
コード例 #18
0
def mail_send_service(from_addr,
                      password,
                      to_addr,
                      content=None,
                      smtp_sever='smtp.qq.com',
                      content_type='plain',
                      filepath=[]):

    #用于构造邮件的from、to以及subject
    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr((Header(name, 'utf-8').encode(), addr))

    #发送方账号、密码
    from_add = from_addr
    password = password
    #接收方账号密码
    to_addr = to_addr
    #smtp服务器地址
    smtp_sever = smtp_sever

    #构造邮件正文及发送人、接收人、主题格式
    msg = MIMEMultipart()

    msg.attach(MIMEText(content, content_type, 'utf-8'))

    # 为邮件添加附件
    if filepath:
        for path, num in zip(filepath, range(len(filepath))):
            filetype = path.split('.')[-1]
            filename = path.split('\\')[-1]
            with open(path, 'rb') as f:
                mime = MIMEBase(None, filetype, filename=filename)
                #加上必要的头信息
                mime.add_header('Content-Disposition',
                                'attachment',
                                filename=filename)
                mime.add_header('Content-ID', '<%s>' % num)
                mime.add_header('X-Attachment-Id', '<%s>' % num)
                #把附件内容读进来
                mime.set_payload(f.read())
                #使用base_64进行编码
                encoders.encode_base64(mime)
                #添加到MIMEMultipart
                msg.attach(mime)

#邮件from、to、object显示内容,可以自行修改
    msg['From'] = _format_addr('Think<%s>' % from_add)
    msg['To'] = _format_addr('You<%s>' % to_addr)
    msg['Subject'] = Header('Thinking...', 'utf-8').encode()

    #执行操作,QQ服务器是通过SSL进行信息传输的
    sever = smtplib.SMTP_SSL('smtp.qq.com', 465)
    # sever.set_debuglevel(1)
    sever.login(from_add, password)
    sever.sendmail(from_add, [to_addr], msg.as_string())
    sever.quit()
コード例 #19
0
ファイル: notificate.py プロジェクト: Jin-Whu/GNSSEvaluate
    def notificate(self, subject, message=None, files=None):
        """notificate.

        Args:
            subject:subject of email.
            message:message of email.
            files:file attacment.
        """
        # read to_addr  and to_name from notificate.ini
        config = readconfig()
        if not config:
            print('Not valid configure\n')
            return

        from_addr = config.from_addr
        from_name = config.from_name
        user = config.email_user
        password = config.email_password
        smtp_server = config.email_server
        smtp_port = config.email_port
        msg = MIMEMultipart()
        msg['From'] = _format_addr('%s <%s>' % (from_name, from_addr))
        msg['To'] = ', '.join([
            _format_addr('%s <%s>' % (to_name, to_addr))
            for to_addr, to_name in zip(config.addr, config.name)
        ])
        msg['Subject'] = Header(subject, 'utf-8').encode()
        if message:
            msg.attach(MIMEText('%s' % message, 'plain', 'utf-8'))
        if files:
            for filepath in files:
                with open(filepath, 'rb') as f:
                    part = MIMEBase('application', 'octet-stream')
                    part.add_header(
                        'Content-Disposition',
                        'attacment',
                        filename=os.path.basename(filepath))
                    part.set_payload(f.read())
                    encoders.encode_base64(part)
                    msg.attach(part)

        while True:
            try:
                server = smtplib.SMTP(smtp_server, smtp_port)
                server.starttls()
                server.login(user, password)
                server.sendmail(from_addr, config.addr, msg.as_string())
                server.quit()
                now = str(datetime.datetime.now().replace(second=0, microsecond=0))
                for to_addr in config.addr:
                    print('%s: Send email to %s successfully!\n' % (now, to_addr))
            except:
                raise
                time.sleep(300)
            else:
                break
コード例 #20
0
def py_attach(file: str):
    file_name = file.split('\\')[-1]
    with open(file, 'rb') as f:
        contype = 'application/octet-stream'
        maintype, subtype = contype.split('/', 1)
        atta = MIMEBase(maintype, subtype, filename=file_name)
        atta.add_header('Content-Disposition',
                        'attachment',
                        filename=file_name)
        atta.add_header('Content-ID', '<0>')
        atta.add_header('X-Attachment-Id', '0')
        atta.set_payload(f.read())
        encoders.encode_base64(atta)
    return atta
コード例 #21
0
    def send_email(self, subject, message, attach_images=None):

        # Email multiple part object
        msg = MIMEMultipart()
        msg['From'] = self.from_addr
        msg['To'] = self.to_addr
        msg['Subject'] = Header(subject, 'utf-8').encode()

        # Attach images and insert them in the html code.
        images_html = None
        if attach_images:
            list_images = []
            for img_id, image in enumerate(attach_images):
                with open(image, 'rb') as f:
                    mime = MIMEBase(os.path.splitext(image)[0],
                                    os.path.splitext(image)[1],
                                    filename=os.path.basename(image))
                    mime.add_header('Content-Disposition',
                                    'attachment',
                                    filename=os.path.basename(image))
                    mime.add_header('X-Attachment-Id', str(img_id))
                    mime.add_header('Content-ID', '<' + str(img_id) + '>')
                    mime.set_payload(f.read())
                    encoders.encode_base64(mime)
                    # Add object to MIMEMultipart object
                    msg.attach(mime)
                    list_images.append("<p><img src='cid:" + str(img_id) +
                                       "'></p>")

            images_html = " \n ".join(list_images)

        # Add object to MIMEMultipart object
        msg_content = MIMEText(
            "<html>"
            "<body>"
            "<h1>RPi Home:</h2>"
            "<h2>" + subject + "</h2>"
            "<h3>" + message + "</h3>"
            "<br>" + (images_html if images_html else "") + "<br>"
            "</body>"
            "</html>", "html", "utf-8")

        msg.attach(msg_content)

        # Connect to the server and send email
        smtp = smtplib.SMTP(self.smtp_server)
        smtp.starttls()
        smtp.login(self.from_addr, self.password)
        smtp.sendmail(self.from_addr, [self.to_addr], msg.as_string())
        smtp.quit()
コード例 #22
0
    def mail_ssrlink(self, user):

        if not re.match(r'.+@.+', user['user']):
            print("Error occured! %s is not a valid email address." %
                  user['user'])
            return

        def _format_addr(s):
            name, addr = parseaddr(s)
            return formataddr((Header(name, 'utf-8').encode(), addr))

        from_addr = const.email
        password = const.mailPassword
        to_addr = user['user']
        smtp_server = 'smtp.gmail.com'
        #smtp_port = 465
        smtp_port = 587

        # email entity:
        msg = MIMEMultipart()
        msg['From'] = _format_addr(const.mailFrom + ' <%s>' % from_addr)
        msg['To'] = _format_addr('%s <%s>' % (to_addr.split('@')[0], to_addr))
        msg['Subject'] = Header(const.mailSubject, 'utf-8').encode()

        # email content:
        msg.attach(
            MIMEText(user['ssrlink'] + '\n\n' + const.mailContent, 'plain',
                     'utf-8'))

        # email attach
        filename = user['user'] + '_qrcode.png'
        newpath = os.path.join(os.path.abspath('.'), 'user_qrcode', filename)
        with open(newpath, 'rb') as f:
            mime = MIMEBase('image', 'png', filename=filename)
            mime.add_header('Content-Disposition',
                            'attachment',
                            filename=filename)
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            mime.set_payload(f.read())
            encoders.encode_base64(mime)
            msg.attach(mime)

        #server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        server = smtplib.SMTP(smtp_server, smtp_port)
        server.starttls()
        server.set_debuglevel(1)
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
コード例 #23
0
ファイル: kmailer_sender.py プロジェクト: devopsmi/KMailer
 def _attach_log_file(mime, file):
     # 添加附件
     if file:
         with open(file, 'rb') as f:
             mime_base = MIMEBase('text',
                                  'log',
                                  filename=log_file_display_name)
             # 加上必要的头信息:
             mime_base.add_header('Content-Disposition',
                                  'attachment',
                                  filename=log_file_display_name)
             mime_base.add_header('Content-ID', '<0>')
             mime_base.add_header('X-Attachment-Id', '0')
             mime_base.set_payload(f.read())
             mime.attach(mime_base)
コード例 #24
0
ファイル: mailingModule.py プロジェクト: tuanh610/WebScraper
    def create_message_with_attachment(self, sender, to, subject, message_text, file):
        message = MIMEMultipart()
        message['to'] = to
        message['from'] = sender
        message['subject'] = subject
        msg = MIMEText(message_text)
        message.attach(msg)

        content_type, encoding = mimetypes.guess_type(file)
        if content_type is None or encoding is not None:
            content_type = 'application/octet-stream'
        main_type, sub_type = content_type.split('/', 1)
        if main_type == 'text':
            fp = open(file, 'rb')
            msg = MIMEText(fp.read(), _subtype=sub_type)
            fp.close()
        elif main_type == 'image':
            fp = open(file, 'rb')
            msg = MIMEImage(fp.read(), _subtype=sub_type)
            fp.close()
        elif main_type == 'audio':
            fp = open(file, 'rb')
            msg = MIMEAudio(file, _subtype=sub_type)
            fp.close()
        else:
            fp = open(file, 'rb')
            msg = MIMEBase(file, _subtype=sub_type)
            fp.close()
        filename = os.path.basename(file)
        msg.add_header('Content-Disposition', 'attachment', filename=filename)
        message.attach(msg)
        return {'raw': base64.urlsafe_b64encode(message.as_string().encode('UTF-8')).decode('ascii')}
コード例 #25
0
 def add_pic(self, fname, refname, pic_id):
     with open(fname, 'rb') as f:
         #  设置附件的MIME和文件名,这里是jpg类型:
         mime = MIMEBase('image', 'jpg', filename=refname)
         # 加上必要的头信息:
         mime.add_header('Content-Disposition',
                         'attachment',
                         filename=refname)
         mime.add_header('Content-ID', '<' + str(pic_id) + '>')
         mime.add_header('X-Attachment-Id', str(pic_id))
         # 把附件的内容读进来:
         mime.set_payload(f.read())
         # 用Base64编码:
         encoders.encode_base64(mime)
         # 添加到MIMEMultipart:
         self.msg.attach(mime)
コード例 #26
0
    def _addAttachment(self, filename, altname=None):
        if not path.isfile(filename) or filename is None:
            return False

        ctype, encoding = mimetypes.guess_type(filename)
        if ctype is None or encoding is not None:
            ctype = 'application/octet-stream'

        maintype, subtype = ctype.split('/', 1)

        if maintype == 'text':
            with open(filename) as fp:
                msg = MIMEText(fp.read(), _subtype=subtype)
        elif maintype == 'image':
            with open(filename, 'rb') as fp:
                msg = MIMEImage(fp.read(), _subtype=subtype)
        elif maintype == 'audio':
            with open(filename, 'rb') as fp:
                msg = MIMEAudio(fp.read(), _subtype=subtype)
        else:
            with open(filename, 'rb') as fp:
                msg = MIMEBase(maintype, subtype)
                msg.set_payload(fp.read())
            encoders.encode_base64(msg)

        msg.add_header(
            'Content-Disposition', 'attachment; filename="%s"' %
            (path.basename(filename) if altname is None else altname))

        self.__attachments.append(msg)

        return True
コード例 #27
0
ファイル: smtp.py プロジェクト: gdcgit/python_study
def mail():
    ret = True
    try:
        # msg = MIMEText('填写邮件内容', 'plain', 'utf-8')  # 纯文本

        # html
        # msg = MIMEText('<html><body><p style="color:red">用Python发邮件</p><a href="https://www.baidu.com">baidu</a>'
        #                '</body></html>', 'html', 'utf-8')

        # msg['From'] = formataddr(['来自高笛淳', my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        # msg['To'] = formataddr(['cc', my_user])  # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        # msg['Subject'] = '测试发邮件'  # 邮件的主题,也可以说是标题
        # msg = MIMEMultipart()
        msg = MIMEMultipart('alternative')
        msg['From'] = _format_addr('Python爱好者<%s>' % my_sender)
        msg['To'] = _format_addr('管理员<%s>' % my_user)
        msg['Subject'] = Header('来自SMTP的问候', 'utf-8').encode()

        # 图片作为附件
        msg.attach(MIMEText('send with file..', 'plain', 'utf-8'))
        msg.attach(MIMEText('<html><body><h1>Hello</h1><p>'
                            '<img style="width:60px,height:80px" src="cid:0"></p></body></html>', 'html', 'utf-8'))

        with open('../resource/timg.jpg', 'rb') as f:
            # 设置附件mime和文件名,这里是png类型
            mime = MIMEBase('image', 'png', filename='tst.jpg')
            # 加上必要的头信息
            mime.add_header('Content-Disposition', 'attachment', filename='tst.jpg')
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')

            # 把附件内容读进来
            mime.set_payload(f.read())
            # 用Base64编码
            encode_base64(mime)
            # 添加到MIMEMultipart
            msg.attach(mime)

        server = smtplib.SMTP_SSL('smtp.qq.com', 465)  # 发件人邮箱中的SMTP服务器,端口是465
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(my_sender, my_user, msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
    except Exception as e:  # 如果 try 中的语句没有执行,则会执行下面的 ret=False
        ret = False
    return ret
コード例 #28
0
def alternative(data, contenttype):
    maintype, subtype = contenttype.split('/')
    if maintype == 'text':
        retival = MIMEText(data, _subtype=subtype)
    else:
        retival = MIMEBase(maintype, subtype)
        retival.set_payload(data)
        encoders.encode_base64(retival)
    return retival
コード例 #29
0
    def mail_ssrlink(self, user):
        def _format_addr(s):
            name, addr = parseaddr(s)
            return formataddr((Header(name, 'utf-8').encode(), addr))

        from_addr = '*****@*****.**'
        password = raw_input('Password: '******'user']
        smtp_server = 'smtp.gmail.com'
        smtp_port = 465

        # email entity:
        msg = MIMEMultipart()
        msg['From'] = _format_addr('hongxing <%s>' % from_addr)
        msg['To'] = _format_addr('%s <%s>' % (to_addr.split('@')[0], to_addr))
        msg['Subject'] = Header("hongxinglink", 'utf-8').encode()

        # email content:
        msg.attach(
            MIMEText(
                user['ssrlink'] + '\n\n' + 'Tutor: ' +
                'https://www.lanzous.com/b348099/\nPassword:16h2', 'plain',
                'utf-8'))

        # email attach
        filename = user['user'] + '_qrcode.png'
        newpath = os.path.join(os.path.abspath('.'), 'user_qrcode', filename)
        with open(newpath, 'rb') as f:
            mime = MIMEBase('image', 'png', filename=filename)
            mime.add_header('Content-Disposition',
                            'attachment',
                            filename=filename)
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            mime.set_payload(f.read())
            encoders.encode_base64(mime)
            msg.attach(mime)

        server = smtplib.SMTP_SSL(smtp_server, smtp_port)
        # server.starttls()
        server.set_debuglevel(1)
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], msg.as_string())
        server.quit()
コード例 #30
0
 def test_does_not_match_multipart_w_no_charset_not_utf8(self):
     """
     Simulates mime messages created by stdlib email parser where  a part
     can have a charset set in the Content-Type header but get_charset()
     returns None.
     """
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     from email.mime.text import MIMEText
     body_text = u'Non \xe8 giusto costringermi ad usare il modulo email.'
     msg = MIMEMultipart()
     body = MIMEText(body_text.encode('ISO-8859-1'))
     body.set_charset(None)
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg), None)
コード例 #31
0
 def test_does_not_match_multipart_w_no_charset_not_utf8(self):
     """
     Simulates mime messages created by stdlib email parser where  a part
     can have a charset set in the Content-Type header but get_charset()
     returns None.
     """
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     from email.mime.text import MIMEText
     body_text = u'Non \xe8 giusto costringermi ad usare il modulo email.'
     msg = MIMEMultipart()
     body = MIMEText(body_text.encode('ISO-8859-1'))
     body.set_charset(None)
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg), None)
コード例 #32
0
 def test_does_not_multipart(self):
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     msg = MIMEMultipart()
     body = MIMEBase('x-application', 'not-text')
     body.set_payload('I am full of happy babies.  All Days for Me!')
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg), None)
コード例 #33
0
 def prepare_attachment(self, path):
     filename = os.path.split(path)[1]
     bookname = filename.split('.')[0]
     booktype = filename.split('.')[1]
     with open(path, 'rb') as f:
         # 设置附件的MIME和文件名,这里是png类型:
         mime = MIMEBase(bookname, booktype, filename=filename)
         # 加上必要的头信息:
         mime.add_header('Content-Disposition',
                         'attachment',
                         filename=filename)
         mime.add_header('Content-ID', '<0>')
         mime.add_header('X-Attachment-Id', '0')
         # 把附件的内容读进来:
         mime.set_payload(f.read())
         # 用Base64编码:
         encoders.encode_base64(mime)
         # 添加到MIMEMultipart:
         return mime
コード例 #34
0
    def sendmail_Accessory(self, subject, body, filepath):

        # 构造MIMEMultipart邮件对象为根容器
        msg = MIMEMultipart()

        # 添加From、To和Subject信息到MIMEText中
        msg['From'] = self._format_addr(u'<%s>' % self.from_addr)
        msg['To'] = self._format_addr(u'<%s>' % ','.join(self.to_addr))
        msg['Subject'] = Header(subject, 'utf-8').encode()

        # 往邮件MIMEMultipart对象里添加MIMEText作为邮件正文,指定编码为utf-8,防止中文乱码
        msg.attach(MIMEText(body, 'plain', 'utf-8'))

        file_type, file_format = mimetypes.guess_type(filepath)[0].split(
            '/', 1)  # 根据 guess_type方法判断文件的类型和格式
        file_name = os.path.basename(filepath)  # 获取文件名

        # 添加附件就是加上一个MIMEBase,读取附件信息
        with open(filepath, 'rb') as f:
            # 设置附件的MIME和文件名,指定文件类型
            mime = MIMEBase(file_type, file_format, filename=file_name)

            # 加上必要的头信息
            # 如果附件名称含有中文, 则 filename 要转换为gb2312编码, 否则附件名称就会出现乱码
            # unicode转换方法:  basename.encode('gb2312')
            # utf-8转换方法:    basename.decode('utf-8').encode('gb2312')
            mime.add_header(
                'Content-Disposition', 'attachment; filename="%s"' %
                file_name.decode('utf8').encode('gb2312'))
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')

            # 把附件的内容读进来
            mime.set_payload(f.read())
            # 用Base64编码格式化
            encoders.encode_base64(mime)

            # 添加到MIMEMultipart
            msg.attach(mime)

        # 发邮件
        return self.sendmail(msg)
コード例 #35
0
ファイル: mail.py プロジェクト: glrh111/python-features
def send_mail_with_file(content, args):
    r_content = '<html><body>' + u'<h1>嘿嘿哈哈</h1>'
    # message obj
    msg = MIMEMultipart()
    msg['From'] = _format_addr(u'小王 <%s>' % sender)
    msg['To'] = _format_addr(u'嘿嘿嘿 <%s>' % ','.join(receivers))
    msg['Subject'] = Header(u'老王准备嘿嘿嘿了', 'utf-8').encode()

 
    # add add_ons
    for idx, img in enumerate(args):
        try:
            with open('img/%s' % img, 'rb') as f:
                filename=str(idx)+'.jpg'
                # set MIME and filename
                # there is a keng
                mime = MIMEBase('image', 'jpg', filename=filename)
                # add header info 
                mime.add_header('Content-Disposition', 'attachment', filename=filename)
                mime.add_header('Content-ID', '<%s>' % idx)
                mime.add_header('X-Attachment-ID', str(idx))
                # add file content
                mime.set_payload(f.read())
                # base64 encode
                encoders.encode_base64(mime)
                # attach with msg
                msg.attach(mime)
                r_content += '<p><img src="cid:%s"></p>' % idx
        except:
            # raise
            continue

    # replace \n with <br /> in content
    # pattern = re.compile('\n')
    # content = re.sub(r'\n', '<br />\n    ', content)

    r_content = prefix + content + prefix + '</body></html>'
    # content text
    msg.attach(MIMEText(r_content, 'html', 'utf-8'))


    # send 
    server = smtplib.SMTP(smtp_server, 25)
    # server.set_debuglevel(1)
    server.login(sender, sender_password)
    server.sendmail(sender, receivers, msg.as_string())
    server.quit()
コード例 #36
0
    def send_mail(self, sender, receiver, subject, text='', attachment=None):
        msg = ''
        message = MIMEMultipart()
        message['From'] = self._format_addr('Robot <%s>' % sender)
        message['To'] = self._format_addr('Master <%s>' % receiver)
        message['Subject'] = Header(subject, 'utf-8')
        message.attach(MIMEText(text, 'plain', 'utf-8'))

        if not attachment is None and os.path.exists(attachment):
            with open(attachment, 'rb') as f:
                mime = MIMEBase('image', 'png', filename='image.png')
                mime.add_header('Content-Disposition',
                                'attachment',
                                filename='image.png')
                mime.add_header('Content-ID', '<0>')
                mime.add_header('X-Attachment-Id', '0')
                mime.set_payload(f.read())
                encoders.encode_base64(mime)
                message.attach(mime)
        self.smtp.sendmail(sender, [receiver], message.as_string())
コード例 #37
0
ファイル: BookPusher.py プロジェクト: panthenia/ebookpusher
 def prepare_attachment(self, path):
     filename = os.path.split(path)[1]
     bookname = filename.split('.')[0]
     booktype = filename.split('.')[1]
     with open(path, 'rb') as f:
         # 设置附件的MIME和文件名,这里是png类型:
         mime = MIMEBase(bookname, booktype, filename=filename)
         # 加上必要的头信息:
         mime.add_header('Content-Disposition', 'attachment', filename=filename)
         mime.add_header('Content-ID', '<0>')
         mime.add_header('X-Attachment-Id', '0')
         # 把附件的内容读进来:
         mime.set_payload(f.read())
         # 用Base64编码:
         encoders.encode_base64(mime)
         # 添加到MIMEMultipart:
         return mime
コード例 #38
0
 def test_matches_multipart_w_bogus_charset_in_content_type(self):
     """
     Simulates mime messages created by stdlib email parser where  a part
     can have a charset set in the Content-Type header but get_charset()
     returns None.
     """
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     from email.mime.text import MIMEText
     msg = MIMEMultipart()
     body = MIMEText('I am full of happy babies.  All days for Me!')
     body.set_charset(None)
     del body['Content-Type']
     body['Content-Type'] = 'text/plain; charset=bogus; flow=groovy'
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg),
                      "body_regexp: body matches u'happy.+days'")
コード例 #39
0
def create_message_html_with_attachment(
    sender, to, subject, message_text, message_html, file
):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart("alternative")
    msg = MIMEText(message_text)
    html = MIMEText(message_html, "html")
    message.attach(msg)
    message.attach(html)

    content_type, encoding = mimetypes.guess_type(file)

    if content_type is None or encoding is not None:
        content_type = "application/octet-stream"
    main_type, sub_type = content_type.split("/", 1)
    if main_type == "text":
        fp = open(file, "rb")
        attach = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == "image":
        fp = open(file, "rb")
        attach = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == "audio":
        fp = open(file, "rb")
        attach = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(file, "rb")
        attach = MIMEBase(main_type, sub_type)
        attach.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(file)
    attach.add_header("Content-Disposition", "attachment", filename=filename)
    msg_mixed = MIMEMultipart()
    msg_mixed["to"] = to
    msg_mixed["from"] = sender
    msg_mixed["subject"] = subject
    msg_mixed.attach(message)
    msg_mixed.attach(attach)

    return {"raw": base64.urlsafe_b64encode(msg_mixed.as_bytes()).decode()}
コード例 #40
0
 def test_matches_multipart_w_bogus_charset_in_content_type(self):
     """
     Simulates mime messages created by stdlib email parser where  a part
     can have a charset set in the Content-Type header but get_charset()
     returns None.
     """
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     from email.mime.text import MIMEText
     msg = MIMEMultipart()
     body = MIMEText('I am full of happy babies.  All days for Me!')
     body.set_charset(None)
     del body['Content-Type']
     body['Content-Type'] = 'text/plain; charset=bogus; flow=groovy'
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg),
                      "body_regexp: body matches u'happy.+days'")
コード例 #41
0
def sendEmailTwo():
    # from_addr = input('From:')
    # password = input('Password:'******'To:')
    # smtp_server = input('SMTP server:')
    from_addr = '*****@*****.**'
    password = '******'
    to_addr = '*****@*****.**'
    smtp_server = 'smtp.qq.com'
    message = MIMEMultipart()
    message.attach(MIMEText('hello , send by Python...', 'plain', 'utf-8'))
    message['From'] = format_addr('Python爱好者 <%s>' % format_addr)
    message['To'] = format_addr('管理员 <%s>' % to_addr)
    message['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

    # 添加附件
    with open('test_zippng.png', 'rb') as f:
        # 设置附件的MIME和文件名
        mime = MIMEBase('image', 'png', filename='test_zippng.png')
        # 加上必要的头信息
        mime.add_header('Content-Disposition',
                        'attachment',
                        filename='test_zippng.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment_Id', '0')
        # 把附件的内容读进来
        mime.set_payload(f.read())
        # 用Base64编码
        encoders.encode_base64(mime)
        # 添加到MIMeMultipart
        message.attach(mime)
    try:
        server = smtplib.SMTP(smtp_server, 465)
        server.starttls()
        server.set_debuglevel(1)
        server.login(from_addr, password)
        server.sendmail(from_addr, [to_addr], message.as_string())
        server.quit()
    except Exception as e:
        print(e)
コード例 #42
0
ファイル: gmail.py プロジェクト: legastero/Weld
    def send(self, to, subject, message, attachments=None):
        """
        Send an email. May also include attachments.

        to          -- The email recipient.
        subject     -- The email subject.
        message     -- The email body.
        attachments -- A list of file names to include.
        """
        if attachments is None:
            attachments = []
        msg = MIMEMultipart()
        msg.attach(MIMEText(message))
        for path in attachments:
            content_type, encoding = mimetypes.guess_type(path)
            if content_type is None or encoding is not None:
                content_type = 'application/octet-stream'

            main_type, subtype = content_type.split('/', 1)

            with open(path, 'rb') as file:
                data = file.read()
                attachment = MIMEBase(main_type, subtype)
                attachment.set_payload(data)
                email.encoders.encode_base64(attachment)

            attachment.add_header('Content-Disposition',
                                  'attachment',
                                  filename=os.path.basename(path))
            msg.attach(attachment)

        msg['To'] = to
        msg['From'] = self.__username
        msg['Subject'] = subject

        log.debug('GMAIL: Sending email to %s' % msg['To'])
        errors = self.smtp.sendmail(self.__username, to, msg.as_string())

        return msg, errors
コード例 #43
0
    def test_matches_multipart_w_comment_in_charset(self):
        """
        At least one email client out there generates content type headers that
        look like::

            Content-Type: text/html; charset="utf-8" //iso-8859-2
        """
        from email.mime.multipart import MIMEMultipart
        from email.mime.multipart import MIMEBase
        from email.mime.text import MIMEText
        msg = MIMEMultipart()
        body = MIMEText('I am full of happy babies.  All days for Me!')
        body.set_charset(None)
        del body['Content-Type']
        body['Content-Type'] = 'text/plain; charset="utf-8" //iso-8859-2'
        msg.attach(body)
        other = MIMEBase('application', 'pdf')
        other.set_payload('Not really a pdf.')
        msg.attach(other)
        fut = self._make_one()
        self.assertEqual(fut(msg),
                         "body_regexp: body matches u'happy.+days'")
コード例 #44
0
def create_message(path):
    "Return a Message object with the file at path attached"
    d, fname = os.path.split(path)

    # create the outer message
    msg = MIMEMultipart()
    msg['From'] = email.utils.formataddr((OPTIONS['name'], OPTIONS['email']))
    
    fname_parts = fname.split('::')
    if len(fname_parts) == 2:
        to_addr, att_name = fname_parts[0], fname_parts[1]
    else:
        raise FeedbackError("Bad filename: %s; can't determine recipient or attachment name" %
                            fname)

    msg['To'] = to_addr
    msg['Subject'] = OPTIONS['feedback_subject']

    # first part: the text/plain message derived from FEEDBACK_MSG
    body = MIMEText(FEEDBACK_MSG % {'signature' : OPTIONS['name']})
    msg.attach(body)

    # second part: attachment 
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    
    f = open(path, 'rb')

    att = MIMEBase(maintype, subtype)
    att.set_payload(f.read())
    email.encoders.encode_base64(att)
    att.add_header('Content-Disposition', 'attachment', filename=att_name)
    msg.attach(att)

    logging.info("Created feedback message for %s from file %s" % (to_addr, path))

    return msg
コード例 #45
0
ファイル: adapters.py プロジェクト: Falmarri/karl
    def attachments(self):
        folder = self._attachments_folder
        if folder is None:
            return [], [], {}

        profile = self.profile
        request = self.request
        attachments = []
        attachment_links = []
        attachment_hrefs = {}
        for name, model in folder.items():
            if profile.alert_attachments == 'link':
                attachment_links.append(name)
                attachment_hrefs[name] = resource_url(model, request)

            elif profile.alert_attachments == 'attach':
                with model.blobfile.open() as f:
                    f.seek(0, 2)
                    size = f.tell()
                    if size > MAX_ATTACHMENT_SIZE:
                        attachment_links.append(name)
                        attachment_hrefs[name] = resource_url(model, request)

                    else:
                        f.seek(0, 0)
                        data = f.read()
                        type, subtype = model.mimetype.split('/', 1)
                        attachment = MIMEBase(type, subtype)
                        attachment.set_payload(data)
                        Encoders.encode_base64(attachment)
                        attachment.add_header(
                            'Content-Disposition',
                            'attachment; filename="%s"' % model.filename)
                        attachments.append(attachment)

        return attachments, attachment_links, attachment_hrefs
コード例 #46
0
 def test_does_not_multipart(self):
     from email.mime.multipart import MIMEMultipart
     from email.mime.multipart import MIMEBase
     msg = MIMEMultipart()
     body = MIMEBase('x-application', 'not-text')
     body.set_payload('I am full of happy babies.  All Days for Me!')
     msg.attach(body)
     other = MIMEBase('application', 'pdf')
     other.set_payload('Not really a pdf.')
     msg.attach(other)
     fut = self._make_one()
     self.assertEqual(fut(msg), None)
コード例 #47
0
ファイル: mail.py プロジェクト: mcherkassky/ib
	def add_figure(self, plt, imgid=1):
		buf = io.BytesIO()
		plt.savefig(buf, format = 'png')
		buf.seek(0)

		msgText = '<br><img src="cid:image{0}"><br>'.format(imgid)
		self.body = self.body + msgText

		part = MIMEBase('application', "octet-stream")
		part.set_payload( buf.read() )
		Encoders.encode_base64(part)
		part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'figure.png')
		part.add_header('Content-ID', '<image{0}>'.format(imgid))
		self.msg.attach(part)

		buf.close() #close buffer
コード例 #48
0
ファイル: sendmail.py プロジェクト: todototry/mailer
    def send(self):
        # 邮件对象:
        msg = MIMEMultipart()
        msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
        msg['To'] = _format_addr('管理员 <%s>' % to_addr)
        msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

        # 邮件正文是MIMEText:
        msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))

        # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
        with open('/Users/michael/Downloads/test.png', 'rb') as f:
            # 设置附件的MIME和文件名,这里是png类型:
            mime = MIMEBase('image', 'png', filename='test.png')
            # 加上必要的头信息:
            mime.add_header('Content-Disposition', 'attachment', filename='test.png')
            mime.add_header('Content-ID', '<0>')
            mime.add_header('X-Attachment-Id', '0')
            # 把附件的内容读进来:
            mime.set_payload(f.read())
            # 用Base64编码:
            encoders.encode_base64(mime)
            # 添加到MIMEMultipart:
            msg.attach(mime)
コード例 #49
0
    def test_matches_multipart(self):
        from email.mime.multipart import MIMEMultipart
        from email.mime.multipart import MIMEBase
        from email.mime.text import MIMEText
        msg = MIMEMultipart()
        body = MIMEText('I am full of happy babies.  All days for Me!')
        msg.attach(body)
        other = MIMEBase('application', 'pdf')
        other.set_payload('Not really a pdf.')
        msg.attach(other)
        fut = self._make_one()
        self.assertEqual(fut(msg),
                         "body_regexp: body matches u'happy.+days'")

        msg = MIMEMultipart()
        body = MIMEText("I can't remember if my amnesia is getting worse.")
        msg.attach(body)
        other = MIMEBase('application', 'pdf')
        other.set_payload('Not really a pdf.')
        msg.attach(other)
        self.assertEqual(fut(msg),
                         "body_regexp: body matches u'amnesia'")
コード例 #50
0
def create_multipart_message(atom_file, binary_file, dat_file):

    # first build the full MIME message using the email library
    msg = MIMEMultipart("related")

    entry = open(atom_file, "rb")
    atom = MIMEBase("application", "atom+xml")
    atom['Content-Disposition'] = 'attachment; name="atom"'
    atom.set_payload(entry.read())
    msg.attach(atom)

    zip = open(binary_file, 'rb')
    base = MIMEBase("application", "zip")
    base['Content-Disposition'] = 'attachment; name="payload"; filename="example.zip"'
    base.set_payload(zip.read())
    encoders.encode_base64(base)
    msg.attach(base)

    # now, to make it work with HTTP pull out the main headers
    headers = {}
    header_mode = True
    body = []
    for line in msg.as_string().splitlines(True):
        if line == "\n" and header_mode:
            header_mode = False
        if header_mode:
            (key, value) = line.split(":", 1)
            headers[key.strip()] = value.strip()
        else:
            body.append(line)
    body = "".join(body)

    # write the body to the dat file
    o = open(dat_file, "wb")
    o.write(body)

    return headers
コード例 #51
0
ファイル: adapters.py プロジェクト: boothead/karl
    def message(self):
        if self._message is not None:
            return self._message

        community = self._community
        request = self.request
        profile = self.profile
        blogentry = self._blogentry

        community_href = model_url(community, request)
        blogentry_href = model_url(blogentry, request)
        manage_preferences_href = model_url(profile, request)
        system_name = get_setting(self.context, "system_name", "KARL")
        system_email_domain = get_setting(self.context, "system_email_domain")

        reply_to = "%s <%s+blog-%s@%s>" % (community.title.replace(',', ''),
                                           community.__name__,
                                           docid_to_hex(blogentry.docid),
                                           system_email_domain)

        attachments = []
        attachment_links = []
        attachment_hrefs = {}
        for name,model in self._attachments.items():
            if profile.alert_attachments == 'link':
                attachment_links.append(name)
                attachment_hrefs[name] = model_url(model, request)

            elif profile.alert_attachments == 'attach':
                with model.blobfile.open() as f:
                    f.seek(0, 2)
                    size = f.tell()
                    if size > MAX_ATTACHMENT_SIZE:
                        attachment_links.append(name)
                        attachment_hrefs[name] = model_url(model, request)

                    else:
                        f.seek(0, 0)
                        data = f.read()
                        type, subtype = model.mimetype.split('/', 1)
                        attachment = MIMEBase(type, subtype)
                        attachment.set_payload(data)
                        Encoders.encode_base64(attachment)
                        attachment.add_header(
                            'Content-Disposition',
                            'attachment; filename="%s"' % model.filename)
                        attachments.append(attachment)

        body_template = get_template(self._template)
        from_name = "%s | %s" % (self.creator.title, system_name)
        msg = MIMEMultipart() if attachments else Message()
        msg["From"] = "%s <%s>" % (from_name, self.mfrom)
        msg["To"] = "%s <%s>" % (profile.title, profile.email)
        msg["Reply-to"] = reply_to
        msg["Subject"] = self._subject
        body_text = body_template(
            context=self.context,
            community=community,
            community_href=community_href,
            blogentry=blogentry,
            blogentry_href=blogentry_href,
            attachments=attachment_links,
            attachment_hrefs=attachment_hrefs,
            manage_preferences_href=manage_preferences_href,
            profile=profile,
            profiles=self.profiles,
            creator=self.creator,
            digest=self.digest,
            alert=self,
            history=self._history,
        )

        if self.digest:
            # Only interested in body for digest
            html = document_fromstring(body_text)
            body_element = html.cssselect('body')[0]
            span = etree.Element("span", nsmap=body_element.nsmap)
            span[:] = body_element[:] # Copy all body elements to an empty span
            body_text = etree.tostring(span, pretty_print=True)

        if isinstance(body_text, unicode):
            body_text = body_text.encode('utf-8')

        if attachments:
            body = MIMEText(body_text, 'html', 'utf-8')
            msg.attach(body)
            for attachment in attachments:
                msg.attach(attachment)
        else:
            msg.set_payload(body_text, 'utf-8')
            msg.set_type("text/html")

        self._message = msg

        return self._message
コード例 #52
0
ファイル: 111.py プロジェクト: wisemanTrap/pythonMailer
msg['Subject'] = 'Гениальность, Архетипы. Барселона.'
msg['From'] = me
msg['To'] = 'Вам'

htmlFile = open("html/genialnosti_table.html", "rU")

htmlFile = htmlFile.read()

part1 = MIMEText(htmlFile, 'html')
#!!!!
part1.set_charset('utf-8')

msg.attach(part1)
#-----------------------------------------------------------------------------------------------------------------------
# add attach file1
part = MIMEBase('application', "octet-stream")
filename = projectPath + "/docs/genialnost/Antonio_Gaudi.docx"

part.set_payload(open(filename, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'Антонио Гауди.docx')
msg.attach(part)
#-----------------------------------------------------------------------------------------------------------------------
# add attach file2
part = MIMEBase('application', "octet-stream")
filename =  projectPath + "/docs/genialnost/Arkhetipy_Sinergia_partnerstva.doc"

part.set_payload(open(filename, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'Архетипы. Синергия партнерства.doc')
msg.attach(part)
コード例 #53
0
ファイル: mailing.py プロジェクト: carlos-gs/MiStuRe
    def enviar_correo(self, correo_dest, asunto, cuerpo, intento=0,
                      *rutas_adjuntos):
        """
        Se envía un correo bajo el nombre indicado a mailer y sobre la conexión
        establecida en este, con los elementos cómunes de un correo, que se
        le pasan como argumentos.
        :param correo_dest:
        :param asunto:
        :param cuerpo:
        :param intento: para indicar el número de reintento.
        :param rutas_adjuntos:
        :return:
        """
        if True in (type(x) is not str for x in (correo_dest, asunto, cuerpo)):
            raise Exception(__name__ + '.sendMail params must be str')

        if self.smtp_host == 'smtp.sendgrid.net':
            origen = '*****@*****.**'
        else:
            origen = self.email_origen
        enviado = False
        # Podríamos verificar cnx sigue, aunque sino ya saltara excepción.
        try:
            # Preparamos las cabeceras de addrs
            fromadrr = Address(self.nombre_origen, addr_spec=origen)
            name, addr = parseaddr(correo_dest)
            toaddr = Address(name, addr_spec=addr)

            # Encapsulamos el mensaje
            msg = MIMEMultipart()  # Para poder combinar fragmentos de <> MIME
            msg['From'] = formataddr((fromadrr.display_name, fromadrr.addr_spec))
            msg['To'] = formataddr((toaddr.display_name, toaddr.addr_spec))
            msg['Subject'] = asunto
            msg['Date'] = format_datetime(localtime())

            # Construir msg (MIME de texto) y añadir al contenedor
            msg.attach(MIMEText(cuerpo, 'plain'))

            #  Adición de los adjuntos, a msg.
            for ruta in rutas_adjuntos:
                rutap = os.path.abspath(ruta)
                if not os.path.exists(rutap):
                    # notificarlo de alguna forma
                    print('{} error:\t fallo adjuntando {} para {}'.format(
                        __name__, rutap, origen))
                    continue
                    
                #with open(rutap) as fp:
                #    part = MIMEText(fp.read(), _subtype='plain')
                part = MIMEBase('application', "octet-stream")
                part.set_payload(open(rutap, "rb").read())
                
                encoders.encode_base64(part)
                #  part.add_header('Content-Disposition',
                #   'attachment; filename="{}"'.format(os.path.basename(rutap)))
                part.add_header('Content-Disposition',
                    'attachment; filename="{}"'.format(os.path.basename(rutap)))
                msg.attach(part)
                

            # server.sendmail(fromadrr.addr_spec, tomail, msg.as_string())
            self.smtpserver.send_message(msg)
            enviado = True
            self._incr_numenviados()

        except SMTPException as smtpe:
            print('RECONECTADO y REENVIO POR EXCEPT')
            if intento < mailer.REINTENTOS and not enviado:
                self._conectar()
                self.enviar_correo(correo_dest, asunto, cuerpo, intento+1,
                                   *rutas_adjuntos)
            else:
                raise
        except:
            raise
コード例 #54
0
ファイル: PicasaPut.py プロジェクト: denirz/PicasaLib
def PostPhoto(Auth, PublisherUserID, AlbumName, PhotoPath, Title="Default Title", Summary="Set  via Picasa API"):
    # POST https://picasaweb.google.com/data/feed/api/user/userID/albumid/albumID
    # https://picasaweb.google.com/data/feed/api/user/userID/albumid/albumID
    """
    Should post the file to the selecter Album
    """
    ListAlbumUrl = "/data/feed/api/user/" + PublisherUserID
    AlbumID = Album_IDfromAlbumName(AlbumName, Auth, ListAlbumUrl)
    PostUrl = "/data/feed/api/user/" + PublisherUserID + "/albumid/" + AlbumID
    #    print "PostUrl:",PostUrl
    # Annotation Forming:
    # To define a spectial Function  for that:
    TextToMime = "<entry xmlns='http://www.w3.org/2005/Atom'><title>"
    TextToMime = TextToMime + Title
    TextToMime = TextToMime + "</title><summary>"
    TextToMime = TextToMime + Summary
    TextToMime = (
        TextToMime
        + "</summary><category scheme='http://schemas.google.com/g/2005#kind' term='http://schemas.google.com/photos/2007#photo'/></entry>"
    )

    # Creating a connection
    Pic_Connection = httplib.HTTPSConnection(Picasa_Host)
    Pic_Connection.set_debuglevel(DEBUG_LEVEL)
    header = {
        "Authorization": "GoogleLogin auth=" + Auth,
        "Content-type": "multipart/related;boundary=END_OF_PART",
        "Accept": "*/*",
        "MIME-Version": "1.0",
    }

    # Creating Multipart Container
    Msg = MIMEMultipart("related", "END_OF_PART")
    # Creatinf XML part
    XmlToAdd = MIMEBase("application", "atom+xml")
    XmlToAdd.set_payload(TextToMime)
    Msg.attach(XmlToAdd)

    # Creating Image part
    FilePath = PhotoPath
    #    FilePath='/Users/denirz/Pictures/Keni.jpg'
    basefile = MIMEBase("image", "jpeg")
    Fd = open(FilePath, "rb")
    basefile.set_payload(Fd.read())
    Fd.close()
    Msg.attach(basefile)

    # now message is ready, so  let's  generate string to post:
    DataToSend = Msg.as_string()
    if DEBUG_LEVEL:
        print "see content in ./message.txt file"
        MsgFile = open("./message.txt", "w")
        MsgFile.write(DataToSend)
        MsgFile.close()

    # now sending rewuest
    Pic_Connection.request("POST", PostUrl, DataToSend, header)
    RetAnswer = Pic_Connection.getresponse()

    #    print RetAnswer.getheaders()
    #    xmlFilePut=open('./post.xml','wb')
    #    xmlFilePut.write(RetAnswer.read())
    #    xmlFilePut.close()

    address = UploadedPictureAddres(RetAnswer.read())
    return address
コード例 #55
0
ファイル: __init__.py プロジェクト: highcat/emailer
    def send(self, emails):
        if isinstance(emails, Email):
            emails = [emails]
        if len([e for e in emails if e.__class__ != Email]):
            raise TypeError('emails must be Email or list of Email instances')

        smtpclass = SMTP_SSL if self.ssl else SMTP
        if self.server == 'localhost':
            smtp = smtpclass(self.server)
        else:
            smtp = smtpclass(self.server, self.port)
        if self.tls:
            smtp.starttls()
        if self.login and self.password:
            smtp.login(self.login, self.password)
        for email in emails:
            c = Charset(email.charset)
            c.header_encoding = QP
            c.body_encoding = 0
            r = Charset(email.charset)
            r.header_encoding = 0
            r.body_encoding = 0

            email.normalize_email_list('rcpt')
            email.normalize_email_list('cc')
            email.normalize_email_list('bcc')
            mime1, mime2 = email.mimetype.split('/')
            mainpart = MIMEBase(mime1, mime2)
            if not email.force_7bit:
                mainpart.set_param('charset', email.charset)

            if len(email.attachments):
                message = MIMEMultipart('mixed')
                message.attach(mainpart)
                del mainpart['mime-version']
            else:
                message = mainpart

            message['Date'] = datetime.datetime.now().strftime(
                '%a, %d %b %Y %H:%M:%S') + (" +%04d" % (time.timezone/-36,))

            h = Header(maxlinelen=1000) # FIXME: what is correct max length?
            fromname = self.fromname.encode(email.charset, 'xmlcharrefreplace')
            h.append(fromname, r if is7bit(fromname) else c)
            h.append('<%s>' % self.email, r)
            message['From'] = h

            message['To'] = email.get_emails_header('rcpt')
            if len(email.cc):
                message['CC'] = email.get_emails_header('cc')
            if len(email.bcc):
                message['BCC'] = email.get_emails_header('bcc')

            subject = email.subject.encode(email.charset, 'xmlcharrefreplace')
            message['Subject'] = Header(subject, r if is7bit(subject) else c)

            if email.reply_to:
                message['Reply-To'] = email.get_emails_header('reply_to')

            if email.force_7bit:
                body = email.body.encode('ascii', 'xmlcharrefreplace')
            else:
                body = email.body.encode(email.charset, 'xmlcharrefreplace')
            mainpart.set_payload(body)

            if is7bit(body):
                mainpart['Content-Transfer-Encoding'] = '7bit'
            else:
                encode_quopri(mainpart)

            for attachment in email.attachments:
                if attachment.__class__ != Attachment:
                    raise TypeError("invalid attachment")

                mimetype = attachment.mimetype
                if not mimetype:
                    mimetype, encoding = guess_type(attachment.filename)
                    if not mimetype:
                        mimetype = 'application/octet-stream'
                mime1, mime2 = mimetype.split('/')
                part = MIMEBase(mime1, mime2)

                # using newer rfc2231 (not supported by Outlook):
                # part.set_param('name', attachment.filename.encode('utf-8'), charset = 'utf-8')

                # hack: using deprecated rfc2047 - supported by Outlook:
                part.set_param('name', str(Header(attachment.filename)))
                del part['mime-version']

                if attachment.id:
                    part['Content-Disposition'] = 'inline'
                else:
                    part['Content-Disposition'] = 'attachment'

                # using newer rfc2231 (not supported by Outlook):
                # part.set_param('filename',
                #                attachment.filename.encode('utf-8'),
                #                'Content-Disposition',
                #                charset = 'utf-8')

                # hack: using deprecated rfc2047 - supported by Outlook:
                part.set_param('filename',
                               str(Header(attachment.filename)),
                               'Content-Disposition')
                if attachment.id:
                    part['Content-ID'] = '<%s>' % attachment.id

                part.set_payload(attachment.content)
                encode_base64(part)

                # Do this AFTER encode_base64(part), or Content-Transfer-Encoding header will duplicate,
                # or even happen 2 times with different values.
                if attachment.charset:
                    part.set_charset(attachment.charset)

                message.attach(part)

            smtp.sendmail(self.email, [rcpt[1] for rcpt in email.rcpt] +
                          [cc[1] for cc in email.cc] +
                          [bcc[1] for bcc in email.bcc], message.as_string())

        smtp.quit()
コード例 #56
0
ファイル: send_mail.py プロジェクト: lifekevin21/LearnPython

from_addr = '*****@*****.**'
password = '******'
to_addr = '*****@*****.**'
smtp_server = 'smtp.126.com'


msg = MIMEMultipart()
msg['From'] = _format_addr('PythonTest <%s>' % from_addr)
msg['To'] = _format_addr('Admin <%s>' % to_addr)
msg['Subject'] = Header('Hello from SMTP...', 'utf-8').encode()

msg.attach(MIMEText('Send with file...', 'plain', 'utf-8'))

with open('E:/pic/test.jpg', 'rb') as f:
    mime = MIMEBase('image', 'png', filename='test.jpg')

    mime.add_header('Content-Disposition', 'attachment', filename='test.hpg')
    mime.add_header('Content-ID', '<0>')
    mime.add_header('X-Attachment-ID', '<0>')

    mime.set_payload(f.read())
    encoders.encode_base64(mime)
    msg.attach(mime)

server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()