本文整理汇总了Python中email.mime.multipart.MIMEBase.set_payload方法的典型用法代码示例。如果您正苦于以下问题:Python MIMEBase.set_payload方法的具体用法?Python MIMEBase.set_payload怎么用?Python MIMEBase.set_payload使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类email.mime.multipart.MIMEBase
的用法示例。
在下文中一共展示了MIMEBase.set_payload方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_msg
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def send_msg(self, to, subject, body, attachments = None):
if attachments:
msg = MIMEMultipart()
msg.attach(MIMEText( body))
else:
msg = MIMEText(body)
msg['To'] = to
msg['From'] = self.__username
msg['Subject'] = subject
if attachments:
for path in attachments:
if not os.path.exists(path):
break
content_type, encoding = mimetypes.guess_type(path)
if content_type is None or encoding is not None:
content_type = 'application/octet-stream'
main_type, subtype = content_type.split('/', 1)
with open(path, 'rb') as file:
data = file.read()
attachment = MIMEBase(main_type, subtype)
attachment.set_payload(data)
email.encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment',
filename = os.path.basename(path))
msg.attach(attachment)
status = self.smtp.sendmail(self.__username, to, msg.as_string())
return status
示例2: newMail
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def newMail(mail_from, mail_to, mail_subj, mail_text, attach_list=[], mail_coding='utf-8'):
"""формирование сообщения"""
multi_msg = MIMEMultipart()
multi_msg['From'] = Header(mail_from, mail_coding)
multi_msg['To'] = Header(mail_to, mail_coding)
multi_msg['Subject'] = Header(mail_subj, mail_coding)
msg = MIMEText(mail_text.encode('utf-8'), 'plain', mail_coding)
msg.set_charset(mail_coding)
multi_msg.attach(msg)
# присоединяем атач-файл
for _file in attach_list:
if exists(_file) and isfile(_file):
with open(_file, 'rb') as fl:
attachment = MIMEBase('application', "octet-stream")
attachment.set_payload(fl.read())
email.encoders.encode_base64(attachment)
only_name_attach = Header(basename(_file), mail_coding)
attachment.add_header('Content-Disposition',\
'attachment; filename="%s"' % only_name_attach)
multi_msg.attach(attachment)
else:
if(attach_file.lstrip() != ""):
print("Файл для атача не найден - %s" %_file)
return multi_msg
示例3: mail
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def mail(mail_to, subject, text, file):
"""send email"""
mailserver = smtplib.SMTP("smtp.gmail.com", 587)
mailserver.starttls()
mailserver.ehlo()
mailserver.login(cred.get('GMAIL','USER'), cred['GMAIL']['PASSWD'])
msg = MIMEMultipart()
text_msg = MIMEText(text, "html")
msg.attach(text_msg)
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
data = open(file, 'rb')
file_msg = MIMEBase(maintype, subtype)
file_msg.set_payload(data.read())
data.close()
email.Encoders.encode_base64(file_msg)
basename = os.path.basename(file)
file_msg.add_header('Content-Disposition', 'attachment', filename=basename)
msg.attach(file_msg)
msg['Date'] = email.Utils.formatdate()
msg['From'] = "[email protected]"
msg['Subject'] = subject
mailserver.sendmail(cred.get('GMAIL', 'USER'), mail_to, msg.as_string())
mailserver.close()
示例4: send_mail
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def send_mail(from_user, pwd, to_user, cc_users, subject, text, attach):
COMMASPACE = ", "
msg = MIMEMultipart("alternative")
#msg = MIMEMultipart()
msg["From"] = from_user
msg["To"] = to_user
msg["Cc"] = COMMASPACE.join(cc_users)
msg["Subject"] = Header(s=subject, charset="utf-8")
msg["Date"] = Utils.formatdate(localtime = 1)
msg.attach(MIMEText(text, "html", _charset="utf-8"))
if (attach != None):
part = MIMEBase("application", "octet-stream")
part.set_payload(open(attach, "rb").read())
Encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment; filename=\"%s\"" % os.path.basename(attach))
msg.attach(part)
smtp_server = "smtp.gmail.com"
port = 587
smtp = smtplib.SMTP(smtp_server, port)
smtp.starttls()
smtp.login(from_user, pwd)
print "gmail login OK!"
smtp.sendmail(from_user, cc_users, msg.as_string())
print "mail Send OK!"
smtp.close()
示例5: _send
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def _send(subject, mail_from, rcpt_to, body, filename):
root_message = MIMEMultipart()
root_message["Subject"] = smtplib.email.Header.Header(subject, "utf-8")
root_message["From"] = mail_from
root_message["To"] = rcpt_to
root_message["Date"] = formatdate()
# 本文
message = MIMEText(body)
message.add_header("Content-Type", "text/plain; charset=UTF-8")
root_message.attach(message)
# 添付ファイル
attachment = MIMEBase("text", "")
attachment_body = _read_text_file(filename)
attachment.set_payload(attachment_body)
encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=filename)
root_message.attach(attachment)
s = smtplib.SMTP("127.0.0.1:25")
composed = root_message.as_string()
s.sendmail(mail_from, [rcpt_to], composed)
s.close()
示例6: notificate
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def notificate(self, subject, message=None, files=None):
"""notificate.
Args:
subject:subject of email.
message:message of email.
files:file attacment.
"""
# read to_addr and to_name from notificate.ini
config = readconfig()
if not config:
print('Not valid configure\n')
return
from_addr = config.from_addr
from_name = config.from_name
user = config.email_user
password = config.email_password
smtp_server = config.email_server
smtp_port = config.email_port
msg = MIMEMultipart()
msg['From'] = _format_addr('%s <%s>' % (from_name, from_addr))
msg['To'] = ', '.join([
_format_addr('%s <%s>' % (to_name, to_addr))
for to_addr, to_name in zip(config.addr, config.name)
])
msg['Subject'] = Header(subject, 'utf-8').encode()
if message:
msg.attach(MIMEText('%s' % message, 'plain', 'utf-8'))
if files:
for filepath in files:
with open(filepath, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.add_header(
'Content-Disposition',
'attacment',
filename=os.path.basename(filepath))
part.set_payload(f.read())
encoders.encode_base64(part)
msg.attach(part)
while True:
try:
server = smtplib.SMTP(smtp_server, smtp_port)
server.starttls()
server.login(user, password)
server.sendmail(from_addr, config.addr, msg.as_string())
server.quit()
now = str(datetime.datetime.now().replace(second=0, microsecond=0))
for to_addr in config.addr:
print('%s: Send email to %s successfully!\n' % (now, to_addr))
except:
raise
time.sleep(300)
else:
break
示例7: test_does_not_multipart
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def test_does_not_multipart(self):
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
msg = MIMEMultipart()
body = MIMEBase('x-application', 'not-text')
body.set_payload('I am full of happy babies. All Days for Me!')
msg.attach(body)
other = MIMEBase('application', 'pdf')
other.set_payload('Not really a pdf.')
msg.attach(other)
fut = self._make_one()
self.assertEqual(fut(msg), None)
示例8: add_figure
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def add_figure(self, plt, imgid=1):
buf = io.BytesIO()
plt.savefig(buf, format = 'png')
buf.seek(0)
msgText = '<br><img src="cid:image{0}"><br>'.format(imgid)
self.body = self.body + msgText
part = MIMEBase('application', "octet-stream")
part.set_payload( buf.read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'figure.png')
part.add_header('Content-ID', '<image{0}>'.format(imgid))
self.msg.attach(part)
buf.close() #close buffer
示例9: send_mail_with_file
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def send_mail_with_file(content, args):
r_content = '<html><body>' + u'<h1>嘿嘿哈哈</h1>'
# message obj
msg = MIMEMultipart()
msg['From'] = _format_addr(u'小王 <%s>' % sender)
msg['To'] = _format_addr(u'嘿嘿嘿 <%s>' % ','.join(receivers))
msg['Subject'] = Header(u'老王准备嘿嘿嘿了', 'utf-8').encode()
# add add_ons
for idx, img in enumerate(args):
try:
with open('img/%s' % img, 'rb') as f:
filename=str(idx)+'.jpg'
# set MIME and filename
# there is a keng
mime = MIMEBase('image', 'jpg', filename=filename)
# add header info
mime.add_header('Content-Disposition', 'attachment', filename=filename)
mime.add_header('Content-ID', '<%s>' % idx)
mime.add_header('X-Attachment-ID', str(idx))
# add file content
mime.set_payload(f.read())
# base64 encode
encoders.encode_base64(mime)
# attach with msg
msg.attach(mime)
r_content += '<p><img src="cid:%s"></p>' % idx
except:
# raise
continue
# replace \n with <br /> in content
# pattern = re.compile('\n')
# content = re.sub(r'\n', '<br />\n ', content)
r_content = prefix + content + prefix + '</body></html>'
# content text
msg.attach(MIMEText(r_content, 'html', 'utf-8'))
# send
server = smtplib.SMTP(smtp_server, 25)
# server.set_debuglevel(1)
server.login(sender, sender_password)
server.sendmail(sender, receivers, msg.as_string())
server.quit()
示例10: prepare_attachment
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def prepare_attachment(self, path):
filename = os.path.split(path)[1]
bookname = filename.split('.')[0]
booktype = filename.split('.')[1]
with open(path, 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase(bookname, booktype, filename=filename)
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename=filename)
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
return mime
示例11: test_does_not_match_multipart_w_no_charset_not_utf8
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def test_does_not_match_multipart_w_no_charset_not_utf8(self):
"""
Simulates mime messages created by stdlib email parser where a part
can have a charset set in the Content-Type header but get_charset()
returns None.
"""
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
from email.mime.text import MIMEText
body_text = u'Non \xe8 giusto costringermi ad usare il modulo email.'
msg = MIMEMultipart()
body = MIMEText(body_text.encode('ISO-8859-1'))
body.set_charset(None)
msg.attach(body)
other = MIMEBase('application', 'pdf')
other.set_payload('Not really a pdf.')
msg.attach(other)
fut = self._make_one()
self.assertEqual(fut(msg), None)
示例12: test_matches_multipart_w_bogus_charset_in_content_type
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def test_matches_multipart_w_bogus_charset_in_content_type(self):
"""
Simulates mime messages created by stdlib email parser where a part
can have a charset set in the Content-Type header but get_charset()
returns None.
"""
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
from email.mime.text import MIMEText
msg = MIMEMultipart()
body = MIMEText('I am full of happy babies. All days for Me!')
body.set_charset(None)
del body['Content-Type']
body['Content-Type'] = 'text/plain; charset=bogus; flow=groovy'
msg.attach(body)
other = MIMEBase('application', 'pdf')
other.set_payload('Not really a pdf.')
msg.attach(other)
fut = self._make_one()
self.assertEqual(fut(msg),
"body_regexp: body matches u'happy.+days'")
示例13: test_matches_multipart_w_comment_in_charset
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def test_matches_multipart_w_comment_in_charset(self):
"""
At least one email client out there generates content type headers that
look like::
Content-Type: text/html; charset="utf-8" //iso-8859-2
"""
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
from email.mime.text import MIMEText
msg = MIMEMultipart()
body = MIMEText('I am full of happy babies. All days for Me!')
body.set_charset(None)
del body['Content-Type']
body['Content-Type'] = 'text/plain; charset="utf-8" //iso-8859-2'
msg.attach(body)
other = MIMEBase('application', 'pdf')
other.set_payload('Not really a pdf.')
msg.attach(other)
fut = self._make_one()
self.assertEqual(fut(msg),
"body_regexp: body matches u'happy.+days'")
示例14: test_matches_multipart
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def test_matches_multipart(self):
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
from email.mime.text import MIMEText
msg = MIMEMultipart()
body = MIMEText('I am full of happy babies. All days for Me!')
msg.attach(body)
other = MIMEBase('application', 'pdf')
other.set_payload('Not really a pdf.')
msg.attach(other)
fut = self._make_one()
self.assertEqual(fut(msg),
"body_regexp: body matches u'happy.+days'")
msg = MIMEMultipart()
body = MIMEText("I can't remember if my amnesia is getting worse.")
msg.attach(body)
other = MIMEBase('application', 'pdf')
other.set_payload('Not really a pdf.')
msg.attach(other)
self.assertEqual(fut(msg),
"body_regexp: body matches u'amnesia'")
示例15: create_message
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import set_payload [as 别名]
def create_message(path):
"Return a Message object with the file at path attached"
d, fname = os.path.split(path)
# create the outer message
msg = MIMEMultipart()
msg['From'] = email.utils.formataddr((OPTIONS['name'], OPTIONS['email']))
fname_parts = fname.split('::')
if len(fname_parts) == 2:
to_addr, att_name = fname_parts[0], fname_parts[1]
else:
raise FeedbackError("Bad filename: %s; can't determine recipient or attachment name" %
fname)
msg['To'] = to_addr
msg['Subject'] = OPTIONS['feedback_subject']
# first part: the text/plain message derived from FEEDBACK_MSG
body = MIMEText(FEEDBACK_MSG % {'signature' : OPTIONS['name']})
msg.attach(body)
# second part: attachment
ctype, encoding = mimetypes.guess_type(path)
if ctype is None or encoding is not None:
ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
f = open(path, 'rb')
att = MIMEBase(maintype, subtype)
att.set_payload(f.read())
email.encoders.encode_base64(att)
att.add_header('Content-Disposition', 'attachment', filename=att_name)
msg.attach(att)
logging.info("Created feedback message for %s from file %s" % (to_addr, path))
return msg