Python Send mail

Source: Internet
Author: User

SMTP Send mail

SMTP is the protocol for messages, Python has built-in support for SMTP, you can send plain text messages, HTML messages, and messages with attachments via Pytho
Where Python only has smtplib and email two modules, email is responsible for the construction of mail, smtplib responsible for mail delivery

1. Start with a plain text email demo

from email.mime.text import MIMETextimport smtplibinfo = MIMEText(‘Hello World‘,‘plain‘,‘utf-8‘)#构造MIMEText对象时,第一个参数是邮件正文,第二个参数是MIME的subtype,‘plain‘表示纯文本,最终MIME就是‘text/plain‘,第三个为字符集 #定义Email地址和密码from_addr = ‘[email protected]‘password = ‘xxxxxx‘#收件人邮箱地址to_user = ‘[email protected]‘#SMTP邮件服务器地址smtp_server = ‘xxx.smtp.com‘s = smtplib.SMTP(smtp_server,25) #定义一个s对象s.set_debuglevel(1) #打印debug日志s.login(from_server,password) #auth发件人信息server.sendmail(from_addr,to_addr,info.as_string())s.quit()

Test, OK can receive mail, but this message does not have the subject and sender information, such mail is easily flagged by the mail management system as spam or even be directly rejected, so we need to add the subject of the message and other information

2. Add a topic to an email message

#!/bin/env python#-*- coding:utf-8 -*-from email import encodersfrom email.header import Headerfrom email.mime.text import MIMETextfrom email.utils import parseaddr, formataddrimport smtplibfrom_addr = ‘xxx‘passwd = ‘xxx‘to_addr = ‘xxx‘smtp_addr = ‘xxx‘def _format_addr(s):    name, addr = parseaddr(s)    return formataddr((Header(name, ‘utf-8‘).encode(), addr))msg = MIMEText(‘Hello 这封是带主题的‘, ‘plain‘, ‘utf-8‘)msg[‘From‘] = _format_addr(‘我是发件人 <%s>‘ % from_addr)msg[‘To‘] = _format_addr(‘收件人 <%s>‘ % to_addr)msg[‘Subject‘] = Header(‘这是邮件主题‘, ‘utf-8‘).encode()s = smtplib.SMTP(smtp_addr,25) #定义一个s对象s.set_debuglevel(1) #打印debug日志s.login(from_addr,passwd) #auth发件人信息s.sendmail(from_addr,to_addr,msg.as_string())s.quit()

Here's a function _format_addr () the address used to format the message

HTML-formatted messages
msg = Mimetext ('

Hello ' +

Send by Python ...

' +
', ' HTML ', ' Utf-8 ')

3. send attachments by big strokes

#!/bin/env python#-*-coding:utf-8-*-from Email import encodersfrom email.header import headerfrom email.mime.text impor T mimetextfrom email.utils import parseaddr, formataddrfrom email.mime.multipart import Mimemultipartfrom Email.mime.image Import mimeimagefrom email.mime.base import mimebaseimport smtplibfrom_addr = ' xxx ' passwd = ' xxx ' to_ addr = ' xxx ' smtp_addr = ' xxx ' def _format_addr (s): name, addr = parseaddr (s) return Formataddr ((Header (name, ' Utf-8 ') . Encode (), addr)) msg = Mimemultipart () msg[' from '] = _format_addr (' I am sender <%s> '% from_addr ') msg[' to '] = _format_addr (' Recipient <%s> '% to_addr) msg[' Subject ' = Header (' This is the subject of the message ', ' utf-8 '). Encode () # The message body is MIMEText:msg.attach (' Mimetext (' Send with file ... ', ' plain ', ' utf-8 ') # Add an attachment that adds a mimebase, reads a picture from the Local: with open ('/tmp/1.png ', ' RB ') as F: # Sets the mime and file of the attachment Name, here is the PNG type: MIME = mimebase (' image ', ' png ', filename= ' 1.png ') # plus the necessary header information: Mime.add_header (' content-disposition ', ' Attachment ', filename= ' 1.png ') Mime.add_header (' Content-id ', ' <0> ') 

Supports both HTML and plain formats
If you send an HTML-formatted message, the recipient will not be able to browse if not supported, so you can choose to support

msg = MIMEMultipart(‘alternative‘)msg[‘From‘] = ...msg[‘To‘] = ...msg[‘Subject‘] = ...msg.attach(MIMEText(‘hello‘, ‘plain‘, ‘utf-8‘))msg.attach(MIMEText(‘

Encrypt SMTP

smtp_server = ‘smtp.gmail.com‘smtp_port = 587server = smtplib.SMTP(smtp_server, smtp_port)server.starttls()# 剩下的代码和前面的一模一样:server.set_debuglevel(1)

Summarize:
Smtplib only need to master the construction method set up a good message at the beginning of the mail can be sent smoothly
Constructs a mail object is a Messag object, if constructs a Mimetext object, on the table a text mail object, if constructs a Mimeimage object, represents one as the attachment picture, wants to combine several objects together, uses the Mimemultipart object, And mimebase can represent any object. Their inheritance relationships are as follows:

 Message +- MIMEBase +- MIMEMultipart +- MIMENonMultipart +- MIMEMessage +- MIMEText +- MIMEImage

Python Send mail

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.