refer to SMTP发送邮件
The simplest one:
from email.mime.text import MIMEText
msg = MIMEText('hello world','plain','utf-8')
sender_mail = input('sender mailbox:')
sender_passwd = input('sender mailbox passward:')
receiver_mail = input('receiver mailbox:')
smtp_addr = input('SMTP server address:')
import smtplib
smtpServer = smtplib.SMTP(smtp_addr,25)
smtpServer.set_debuglevel(1)
smtpServer.login(sender_mail,sender_passwd)
smtpServer.sendmail(sender_mail,[receiver_mail],msg.as_string())
smtpServer.quit()
I want to add the object of ‘From’,’To’ and ‘Subject’:
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr,formataddr
import smtplib
def formatEmailAddr(rawData):
name,addr = parseaddr(rawData)
return formataddr((Header(name,'utf-8').encode(),addr))
sender_mail = input('sender mailbox:')
sender_passwd = input('sender mailbox passward:')
receiver_mail = input('receiver mailbox:')
smtp_addr = input('SMTP server address:')
#handle the content of this email
msg = MIMEText('hello world','plain','utf-8')
msg['From'] = formatEmailAddr('SMTP email sender<%s>' %(sender_mail))
msg['To'] = formatEmailAddr('SMTP email receiver<%s>' %(receiver_mail))
msg['Subject'] = Header('It is a learning code','utf-8').encode()
#send progress
smtpServer = smtplib.SMTP(smtp_addr,25)
smtpServer.set_debuglevel(1)
smtpServer.login(sender_mail,sender_passwd)
smtpServer.sendmail(sender_mail,[receiver_mail],msg.as_string())
smtpServer.quit()
I want to send the HTML pattern email:
#modify the content of the ‘MIMEText’ with 'html' pattern
msg = MIMEText('<html><body><h1>Hello</h1>' +
'<p>send by <a href="http://www.python.org">Python</a>...</p>' +
'</body></html>', 'html', 'utf-8')
I want to add an attachment,modify the msg which will be sent:
msg = MIMEMultipart()
msg['From'] = formatEmailAddr('SMTP email sender<%s>' %(sender_mail))
msg['To'] = formatEmailAddr('SMTP email receiver<%s>' %(receiver_mail))
msg['Subject'] = Header('It is a learning code','utf-8').encode()
msg.attach(MIMEText('hello world', 'plain', 'utf-8'))
with open('/Users/wuxiao/Downloads/test.png', 'rb') as f:
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())
encoders.encode_base64(mime)
msg.attach(mime)
send both HTML and Plain pattern message:
msg = MIMEMultipart('alternative')
msg['From'] = formatEmailAddr('SMTP email sender<%s>' %(sender_mail))
msg['To'] = formatEmailAddr('SMTP email receiver<%s>' %(receiver_mail))
msg['Subject'] = Header('It is a learning code','utf-8').encode()
msg.attach(MIMEText('hello world', 'plain', 'utf-8'))
msg.attach(MIMEText('<html><body><h1>Hello World</h1></body></html>', 'html', 'utf-8'))