【问题标题】:Emailing with an attachment with Python使用 Python 发送带有附件的电子邮件
【发布时间】:2020-09-16 07:43:36
【问题描述】:
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)?

【问题讨论】:

标签: python python-3.x email mime


【解决方案1】:

您需要使用“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())

【讨论】:

  • mail.attach[MIMEText(sent_body,'html')] TypeError: 'method' object is not subscriptable
  • 检查我更新了代码,上面的错误正在显示,我试图从 2days @PN7 解决它
  • 嗨,mail.attach[MIMEText(sent_body,'html')] 应该是 mail.attach(MIMEText(sent_body,'html'))
  • 嗨,兄弟,我查看了很多关于 google 和不同代码的文档,但我无法解决以下错误 ctype,encoding = mimetypes.guess_type(_file) NameError: name 'mimetypes' is not已定义 idk 是什么错误,但如果你帮助我,这将非常有帮助,感谢您的帮助
  • 'mimetypes' 是一个 python 模块。只需“导入 mimetypes”
【解决方案2】:
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' 

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

【讨论】:

    猜你喜欢
    • 2014-11-09
    • 2017-02-04
    • 2019-11-21
    • 2021-12-22
    • 2015-09-09
    相关资源
    最近更新 更多