发送带有 Python 附件的电子邮件

Emailing with an attachment with Python

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

def sem():
    if not os.path.isfile('key.txt'):
        print('below details are req to send report')
        gmail_user = input('enter your email=')
        gmail_app_password = input('enter your email password=')
        print('pls accept the login in your gmail account ')
        ke = open('key.txt',mode="w+") 
        ke.write(gmail_user)
        ke.write(':')
        ke.write(gmail_app_password)
        ke.close()
    if not os.path.isfile('sto.txt'):
        gmai = input('enter the  email to send report=')
        ke = open('sto.txt',mode="w+") 
        ke.write(gmai)
        ke.close()


    with open('key.txt',mode="r")as f:
        ds=f.readlines()
        d=''.join(ds)
        r=d.split(':')
    with open('sto.txt',mode="r")as f:
        ds=f.readlines()


    f=ds
    print(f)
    gmail_user = r[0]
    gmail_app_password = r[1]



    sent_from = gmail_user
    sent_to = ds
    sent_subject = "hey amo lio ,how are ?"
    sent_body = ("Hey, what's up? friend!")

    email_text = """\
    To: %s
    Subject: %s

    %s
    """ % (", ".join(sent_to), sent_subject, sent_body)
    mail = MIMEMultipart()
    mail["Subject"] = sent_subject
    mail["From"] = sent_from
    mail["To"] = sent_to
    mail.attach[MIMEText(sent_body,'html')]

    ctype, encoding = mimetypes.guess_type(_file)
    maintype, subtype = ctype.split('/', 1)
    fp = open("./data/mood.txt")
    msg = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
    filename = os.path.basename(_file)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    mail.attach(msg)
    print('done')
    server.sendmail(sent_from, sent_to, mail.as_string())
    try:
        server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
        server.ehlo()
        server.login(gmail_user, gmail_app_password)
        server.sendmail(sent_from, sent_to, email_text)
        server.close()

        print('Email sent!')
    except Exception as exception:
        print("Error: %s!\n\n" % exception)

sem()

如何在此电子邮件中附加 helloword.txt 文件?这段代码工作正常,我只想发送一个附件。这段代码让我可以在没有任何附件的情况下发送正文。另外,如何加密存储电子邮件地址和密码的 key.txt 文件,并发送电子邮件需要输入密码(diff pass)?

您需要使用 'MIMEMultipart' 模块来附加文件。

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

mail = MIMEMultipart()
mail["Subject"] = sent_subject
mail["From"] = sent_from
mail["To"] = sent_to
mail.attach(MIMEText(sent_body,'html'))

ctype, encoding = mimetypes.guess_type(_file)
maintype, subtype = ctype.split('/', 1)
fp = open("/path/to/attachment/file.txt")
# If file mimetype is video/audio use respective email.mime module. 
# Here assuming 'maintype' == 'text' we will use MIMEText
msg = MIMEText(fp.read(), _subtype=subtype)
fp.close()
filename = os.path.basename(_file)
msg.add_header('Content-Disposition', 'attachment', filename=filename)
mail.attach(msg)


server.sendmail(sent_from, sent_to, mail.as_string())
import smtplib
import mechanize
import os
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText 
from email.mime.base import MIMEBase 
from email import encoders 
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import mimetypes
import pdb

def email:
    sender_address = gmail_user
     #make it input
    receiver_address = gmail_user
    #Setup the MIME
    fromaddr = gmail_user
    sendto =  gmail_app_password
    sender_pass = gmail_app_password = input('enter your email password')
    msg = MIMEMultipart()
    msg['From'] = fromaddr
    msg['To'] = sendto
    msg['Subject'] = 'This is cool'
    body = "this is the body of the text message"
    msg.attach(MIMEText(body, 'plain'))
    filename = 'mood.txt'
    attachment = open('./data/mood.txt', 'rb')
    part = MIMEBase('application', "octet-stream")
    part.set_payload((attachment).read())
    encoders.encode_base64(part)
    part.add_header('Content-Disposition', 'attachment; filename= %s' % filename)
    msg.attach(part)
    smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
    smtpObj.ehlo()
    smtpObj.starttls()
    smtpObj.login(gmail_user, gmail_app_password)
    text = msg.as_string()
    smtpObj.sendmail(fromaddr, sendto , text)
    smtpObj.quit()    # attach the instance 'p' to instance 'msg' 

这里是发送电子邮件的完美工作代码