本文整理汇总了Python中email.mime.multipart.MIMEBase.add_header方法的典型用法代码示例。如果您正苦于以下问题:Python MIMEBase.add_header方法的具体用法?Python MIMEBase.add_header怎么用?Python MIMEBase.add_header使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类email.mime.multipart.MIMEBase
的用法示例。
在下文中一共展示了MIMEBase.add_header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: send_msg
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [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 add_header [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 add_header [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 add_header [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 add_header [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 add_header [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: add_figure
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [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
示例8: create_message
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [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
示例9: send
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [as 别名]
def send(self, to, subject, message, attachments=None):
"""
Send an email. May also include attachments.
to -- The email recipient.
subject -- The email subject.
message -- The email body.
attachments -- A list of file names to include.
"""
if attachments is None:
attachments = []
msg = MIMEMultipart()
msg.attach(MIMEText(message))
for path in attachments:
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)
msg['To'] = to
msg['From'] = self.__username
msg['Subject'] = subject
log.debug('GMAIL: Sending email to %s' % msg['To'])
errors = self.smtp.sendmail(self.__username, to, msg.as_string())
return msg, errors
示例10: attachments
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [as 别名]
def attachments(self):
folder = self._attachments_folder
if folder is None:
return [], [], {}
profile = self.profile
request = self.request
attachments = []
attachment_links = []
attachment_hrefs = {}
for name, model in folder.items():
if profile.alert_attachments == 'link':
attachment_links.append(name)
attachment_hrefs[name] = resource_url(model, request)
elif profile.alert_attachments == 'attach':
with model.blobfile.open() as f:
f.seek(0, 2)
size = f.tell()
if size > MAX_ATTACHMENT_SIZE:
attachment_links.append(name)
attachment_hrefs[name] = resource_url(model, request)
else:
f.seek(0, 0)
data = f.read()
type, subtype = model.mimetype.split('/', 1)
attachment = MIMEBase(type, subtype)
attachment.set_payload(data)
Encoders.encode_base64(attachment)
attachment.add_header(
'Content-Disposition',
'attachment; filename="%s"' % model.filename)
attachments.append(attachment)
return attachments, attachment_links, attachment_hrefs
示例11: send_mail_with_file
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [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()
示例12: prepare_attachment
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [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
示例13: send
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [as 别名]
def send(self):
# 邮件对象:
msg = MIMEMultipart()
msg['From'] = _format_addr('Python爱好者 <%s>' % from_addr)
msg['To'] = _format_addr('管理员 <%s>' % to_addr)
msg['Subject'] = Header('来自SMTP的问候……', 'utf-8').encode()
# 邮件正文是MIMEText:
msg.attach(MIMEText('send with file...', 'plain', 'utf-8'))
# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open('/Users/michael/Downloads/test.png', 'rb') as f:
# 设置附件的MIME和文件名,这里是png类型:
mime = MIMEBase('image', 'png', filename='test.png')
# 加上必要的头信息:
mime.add_header('Content-Disposition', 'attachment', filename='test.png')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-Id', '0')
# 把附件的内容读进来:
mime.set_payload(f.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
示例14: MIMEText
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [as 别名]
htmlFile = htmlFile.read()
part1 = MIMEText(htmlFile, 'html')
#!!!!
part1.set_charset('utf-8')
msg.attach(part1)
#-----------------------------------------------------------------------------------------------------------------------
# add attach file1
part = MIMEBase('application', "octet-stream")
filename = projectPath + "/docs/genialnost/Antonio_Gaudi.docx"
part.set_payload(open(filename, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'Антонио Гауди.docx')
msg.attach(part)
#-----------------------------------------------------------------------------------------------------------------------
# add attach file2
part = MIMEBase('application', "octet-stream")
filename = projectPath + "/docs/genialnost/Arkhetipy_Sinergia_partnerstva.doc"
part.set_payload(open(filename, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % 'Архетипы. Синергия партнерства.doc')
msg.attach(part)
#-----------------------------------------------------------------------------------------------------------------------
# add attach file3
part = MIMEBase('application', "octet-stream")
filename = projectPath + "/docs/genialnost/kurs_po_raskrytiyu_potentsiala_2.doc"
示例15: MIMEMultipart
# 需要导入模块: from email.mime.multipart import MIMEBase [as 别名]
# 或者: from email.mime.multipart.MIMEBase import add_header [as 别名]
from_addr = '[email protected]'
password = 'life901106ntes'
to_addr = '[email protected]'
smtp_server = 'smtp.126.com'
msg = MIMEMultipart()
msg['From'] = _format_addr('PythonTest <%s>' % from_addr)
msg['To'] = _format_addr('Admin <%s>' % to_addr)
msg['Subject'] = Header('Hello from SMTP...', 'utf-8').encode()
msg.attach(MIMEText('Send with file...', 'plain', 'utf-8'))
with open('E:/pic/test.jpg', 'rb') as f:
mime = MIMEBase('image', 'png', filename='test.jpg')
mime.add_header('Content-Disposition', 'attachment', filename='test.hpg')
mime.add_header('Content-ID', '<0>')
mime.add_header('X-Attachment-ID', '<0>')
mime.set_payload(f.read())
encoders.encode_base64(mime)
msg.attach(mime)
server = smtplib.SMTP(smtp_server, 25)
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()