繁体   English   中英

我的练习 Email 与 Python 中的 EmailMessage

[英]My Practice Email with EmailMessage in Python

我正在学习如何通过 python 发送 email。 我使用EmailMessage设置了一些东西,但我不确定我的错误试图在 set_content 行中告诉我什么。

代码:

Email_Address = os.environ.get('Email_User') #email address variable
Email_Password = os.environ.get('Email_Pass') #email password variable
msg = EmailMessage() #making an email class object
msg['Subject'] = 'That_thing' #subject line
msg['From'] = Email_Address #from address line
msg['To'] = Email_Address #to address line. can be made into a list variable for multiple receivers
msg.set_content('Did you get that thing I sent you?') # email body
with open('that_thing.jpeg', 'rb') as f: #rb==read bytes
    file_data = f.read()
    file_type = imghdr.what(f.name)
    file_name = f.name
msg.add_attachment(filedata=file_data, maintype='image', subtype=file_type, filename=file_name)
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: #using smtp on secure socket layer to log in and send email
    smtp.login(Email_Address, Email_Password) #user login information
    smtp.send_message(msg) #sending the actual email

错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-6-3336c41d40e5> in <module>
     13     file_type=imghdr.what(f.name)
     14     file_name=f.name
---> 15 msg.add_attachment(filedata=file_data,maintype='image',subtype=file_type,filename=file_name)
     16 with smtplib.SMTP_SSL('smtp.gmail.com',465) as smtp: #using smtp on secure socket layer to log in and send email
     17     smtp.login(Email_Address,Email_Password) #user login information

~\Anaconda3\lib\email\message.py in add_attachment(self, *args, **kw)
   1145 
   1146     def add_attachment(self, *args, **kw):
-> 1147         self._add_multipart('mixed', *args, _disp='attachment', **kw)
   1148 
   1149     def clear(self):

~\Anaconda3\lib\email\message.py in _add_multipart(self, _subtype, _disp, *args, **kw)
   1133             getattr(self, 'make_' + _subtype)()
   1134         part = type(self)(policy=self.policy)
-> 1135         part.set_content(*args, **kw)
   1136         if _disp and 'content-disposition' not in part:
   1137             part['Content-Disposition'] = _disp

~\Anaconda3\lib\email\message.py in set_content(self, *args, **kw)
   1160 
   1161     def set_content(self, *args, **kw):
-> 1162         super().set_content(*args, **kw)
   1163         if 'MIME-Version' not in self:
   1164             self['MIME-Version'] = '1.0'

~\Anaconda3\lib\email\message.py in set_content(self, content_manager, *args, **kw)
   1090         if content_manager is None:
   1091             content_manager = self.policy.content_manager
-> 1092         content_manager.set_content(self, *args, **kw)
   1093 
   1094     def _make_multipart(self, subtype, disallowed_subtypes, boundary):

TypeError: set_content() missing 1 required positional argument: 'obj'

我正在观看的视频与我的方式相同,并且他们没有收到错误。

任何帮助表示赞赏。

更新:第一个问题已解决。 我有 my.py 作为 Email 使它认为它正在导入自己。 现在要弄清楚附件。

更新:

我让它工作。 搜索错误后,我了解到imghdr有一个已知问题。 找到了 imghdr / python - 无法检测某些图像的类型(图像扩展名) ,其中包含修复问题的补丁。

来自imghdr / python - 无法检测某些图像的类型(图像扩展名) '''

# Monkeypatch bug in imagehdr
from imghdr import tests

def test_jpeg1(h, f):
    """JPEG data in JFIF format"""
    if b'JFIF' in h[:23]:
        return 'jpeg'


JPEG_MARK = b'\xff\xd8\xff\xdb\x00C\x00\x08\x06\x06' \
            b'\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f'

def test_jpeg2(h, f):
    """JPEG with small header"""
    if len(h) >= 32 and 67 == h[5] and h[:32] == JPEG_MARK:
        return 'jpeg'


def test_jpeg3(h, f):
    """JPEG data in JFIF or Exif format"""
    if h[6:10] in (b'JFIF', b'Exif') or h[:2] == b'\xff\xd8':
        return 'jpeg'

tests.append(test_jpeg1)
tests.append(test_jpeg2)
tests.append(test_jpeg3)

'''

请参阅 [https://docs.python.org/3.9/library/email.examples.html],第三个示例。 事实证明,这里唯一的“致命”错误是对文件内容使用命名参数( msg.add_attachment(filedata=file_data );此方法没有命名参数filedata 。请参阅下面的示例代码以获取建议的改进:

import email.message as em
import imghdr
import smtplib

sender = os.environ.get('Email_User')
addressee = sender
smtpaddr = "smtp.gmail.com"
passwd = os.environ.get('Email_Pass')
port = 465
if __name__ == "__main__":
    msg = em.EmailMessage()
    msg['Subject'] = 'That_thing'
    msg['From'] = sender
    msg['To'] = addressee
    msg.set_content('Did you get that thing I sent you?')
    with open('small picture.png', 'rb') as f:
        file_data = f.read()
        file_type = imghdr.what(None, file_data)
        file_name = f.name
    msg.add_attachment(file_data,
                       maintype='image',
                       subtype=file_type)
    with smtplib.SMTP_SSL(smtpaddr, port) as smtp:
        smtp.login(sender, passwd)
        del passwd
        smtp.send_message(msg)
    print(f"Email sent to {addressee}")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM