Python 发电子邮件示例

时间:2023-01-11 07:16:57


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# python 3.5

import re
import os
import smtplib
from io import StringIO
from validate_email import validate_email
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class PYMAIL:
def __init__(self):
self.from_mail = "xxxxx@139.com"
self.from_mail_pwd = "xxxxx"
self.smtp_server = "smtp.139.com"
self.smtp_port = 25

"""
def send_mail(self, to_mail,subject,content):
try:
msg = MIMEText( content ,'plain','utf-8')
msg['From'] = self.from_mail
msg['To'] = to_mail
msg['Subject'] = subject
smtp = smtplib.SMTP(self.smtp_server, self.smtp_port)
smtp.starttls()
smtp.login(self.from_mail , self.from_mail_pwd)
smtp.sendmail(self.from_mail, to_mail, msg.as_string())
smtp.quit()
print("发送成功!")
except smtplib.SMTPException as err:
print("发送失败!")
print(str(err))
"""
def check_mail(self ,maillist):
to_maillist = []
if maillist:
for mail in maillist:
if re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', mail):
if validate_email(mail,verify=True) != None:
to_maillist.append(mail)
else:
raise Exception("Invalid email address: %s" % mail)
else:
raise Exception("Invalid email format: %s" % mail)
else:
raise Exception("Receive email can not be null!")
return to_maillist

#Can add attachment or not.
def send_mail_with_attachment(self, to_mail,subject,content,filelist):
to_maillist = self.check_mail(to_mail)
try:
msg = MIMEMultipart()
msg['From'] = self.from_mail
msg['To'] = ", ".join(to_maillist)
msg['Subject'] = subject
msg.attach(MIMEText( content ,'plain','utf-8'))

#add attachment
if filelist:
for file in filelist:
if os.path.isfile(file):
path, filename = os.path.split(file)
part = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
part["Content-Disposition"] = 'attachment; filename="%s"' % os.path.basename(filename)
msg.attach(part)
else:
raise Exception("The file [%s] is not exists!" % file)

smtp = smtplib.SMTP(self.smtp_server, self.smtp_port)
smtp.starttls()
smtp.login(self.from_mail , self.from_mail_pwd)
smtp.sendmail(self.from_mail, to_maillist, msg.as_string())
smtp.quit()
print("Mail Success!")
except smtplib.SMTPException as err:
print("Mail failure!")
print(str(err))


if __name__ == "__main__":
to_mail = ["xxxxx1@qq.com","xxxxx2@qq.com"]
subject = "test subject"
content = "test mail!~"
filelist = ["D:/Python35/mypy/test.py","D:/Python35/mypy/op.py"]
mymail = PYMAIL()
mymail.send_mail_with_attachment(to_mail,subject,content,filelist)