0

我正在使用链接https://stackabuse.com/how-to-send-emails-with-gmail-using-python/中的代码 它运行良好。我附上了参考代码(第一个代码)。但是,然后我尝试将大部分代码放在一个类中(第二个代码)。邮件还在发送。但是,现在它没有了主体,大部分的身体都消失了。它被发送到一个荒谬的地址。但是,出于某种奇怪的原因,密件抄送包含正确的电子邮件地址。我附上了下面电子邮件的屏幕截图。我是python的新手,所以我不知道我哪里出错了。

import smtplib

gmail_user = 'you@gmail.com'
gmail_password = 'P@ssword!'

sent_from = gmail_user
to = ['me@gmail.com', 'bill@gmail.com']
subject = 'OMG Super Important Message'
body = 'Hey, what is up?\n\n- You'

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

%s
""" % (sent_from, ", ".join(to), subject, body)

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()

    print 'Email sent!'
except:
    print 'Something went wrong...'
    import smtplib
    class emailInfo:
        user='Y@gmail.com'
        password = 'XXXX'
        sent_from = user
        to = []
        subject =''
        body =''
        email_text=''
        def createEmailText(self):
            return """\
            From: %s
            To: %s
            Subject: %s
            %s
            """ % (self.sent_from, ", ".join(self.to), self.subject, self.body)
        def send_email(self):
            server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
            server.ehlo()
            server.login(self.user, self.password)
            server.sendmail(self.sent_from, self.to, self.email_text)
            server.close()

    try:
        myEmail=emailInfo()
        myEmail.body='Hey, what is up buddy?\n\n- You'
        myEmail.subject='OMG Super Important Message 2'
        myEmail.to=['Z@gmail.com']
        myEmail.email_text=myEmail.createEmailText()
        myEmail.send_email()
        print('Email sent!')
    except:
        print('Something went wrong...')

不正确的电子邮件屏幕截图

4

0 回答 0