The email module in python makes it easier to process emails. This article mainly introduces the main methods of sending various types of emails in python. Those who are interested can learn more.
The email module in python makes it easier to process emails. Today I focus on learning the specific methods of sending emails. I will write down my own experience here and ask experts for some advice.
1. Introduction to related modules
Sending emails mainly uses two modules: smtplib and email. Here is a brief introduction to the two modules:
1. smtplib module
smtplib.SMTP([host[, port[, local_hostname[, timeout]]]])
SMTP class The constructor represents the connection with the SMTP server. Through this connection, you can send instructions to the SMTP server and perform related operations (such as logging in, sending emails). All parameters are optional.
host: SMTP server host name
port: SMTP service port, the default is 25; if these two parameters are provided when creating the SMTP object, they will be automatically called during initialization connect method to connect to the server.
The smtplib module also provides the SMTP_SSL class and LMTP class, and their operations are basically the same as SMTP.
Methods provided by smtplib.SMTP:
SMTP.set_debuglevel(level): Set whether it is in debug mode. The default is False, which is non-debugging mode, which means no debugging information is output.
SMTP.connect([host[, port]]): Connect to the specified SMTP server. The parameters represent the smpt host and port respectively. Note: You can also specify the port number in the host parameter (eg: smpt.yeah.net:25), so there is no need to give the port parameter.
SMTP.docmd(cmd[, argstring]): Send instructions to the smtp server. The optional parameter argstring represents the parameters of the instruction.
SMTP.helo([hostname]): Use the "helo" command to confirm identity to the server. It is equivalent to telling the SMTP server "who I am".
SMTP.has_extn(name): Determine whether the specified name exists in the server mailing list. For security reasons, SMTP servers often block this command.
SMTP.verify(address): Determine whether the specified email address exists in the server. For security reasons, SMTP servers often block this command.
SMTP.login(user, password): Log in to the SMTP server. Almost all SMTP servers now must verify that the user information is legitimate before allowing emails to be sent.
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]): Send mail. Pay attention to the third parameter here. msg is a string representing an email. We know that emails generally consist of a title, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the format of msg. This format is the format defined in the smtp protocol.
SMTP.quit(): Disconnect from the SMTP server, which is equivalent to sending the "quit" command. (smtp.close() is used in many programs. I googled the difference between quit and quit, but I couldn’t find the answer.)
2. Email module
The emial module is used to process email messages, including MIME and other RFC 2822-based message documents. It is very simple to use these modules to define the content of emails. The classes it includes are (more detailed introduction can be found at: http://www.php.cn/):
class email.mime.base.MIMEBase(_maintype, _subtype, **_params): This is A base class for MIME. There is generally no need to create an instance when using it. Where _maintype is the content type, such as text or image. _subtype is the minor type of content, such as plain or gif. **_params is a dictionary passed directly to Message.add_header().
class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]]: A subclass of MIMEBase, a collection of multiple MIME objects, the default value of _subtype is mixed. boundary is the boundary of MIMEMultipart. The default boundary is countable.
class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]]): A subclass of MIMEMultipart. .
class email.mime.audio.MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]]): MIME audio object
class email.mime.image.MIMEImage (_imagedata[, _subtype[, _encoder[, **_params]]]): MIME binary file object.
class email.mime.message.MIMEMessage(_msg[, _subtype]): A specific message instance. , the usage method is as follows:
msg=mail.Message.Message() #一个实例 msg['to']='XXX@XXX.com' #发送到哪里 msg['from']='YYY@YYYY.com' #自己的邮件地址 msg['date']='2012-3-16' #时间日期 msg['subject']='hello world' #邮件主题
class email.mime.text.MIMEText(_text[, _subtype[, _charset]]): MIME text object, where _ Text is the email content, _subtype email type, which can be text/plain (ordinary text email), html/plain (html email), _charset encoding, which can be gb2312, etc.
2. Several. Specific implementation code of email
1. Ordinary text email
The key to the implementation of sending ordinary text email is to set _subtype in MIMEText to plain. First import smtplib and mimetext. Create an smtplib.smtp instance, connect to the email smtp server, and send it after logging in. The specific code is as follows: (implemented under python2.6)
# -*- coding: UTF-8 -*- ''' 发送txt文本邮件 ''' import smtplib from email.mime.text import MIMEText mailto_list=[YYY@YYY.com] mail_host="smtp.XXX.com" #设置服务器 mail_user="XXXX" #用户名 mail_pass="XXXXXX" #口令 mail_postfix="XXX.com" #发件箱的后缀 def send_mail(to_list,sub,content): me="hello"+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content,_subtype='plain',_charset='gb2312') msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user,mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail(mailto_list,"hello","hello world!"): print "发送成功" else: print "发送失败"
2. Sending html emails
与text邮件不同之处就是将将MIMEText中_subtype设置为html。具体代码如下:(python2.6下实现)
# -*- coding: utf-8 -*- ''' 发送html文本邮件 ''' import smtplib from email.mime.text import MIMEText mailto_list=["YYY@YYY.com"] mail_host="smtp.XXX.com" #设置服务器 mail_user="XXX" #用户名 mail_pass="XXXX" #口令 mail_postfix="XXX.com" #发件箱的后缀 def send_mail(to_list,sub,content): #to_list:收件人;sub:主题;content:邮件内容 me="hello"+"<"+mail_user+"@"+mail_postfix+">" #这里的hello可以任意设置,收到信后,将按照设置显示 msg = MIMEText(content,_subtype='html',_charset='gb2312') #创建一个实例,这里设置为html格式邮件 msg['Subject'] = sub #设置主题 msg['From'] = me msg['To'] = ";".join(to_list) try: s = smtplib.SMTP() s.connect(mail_host) #连接smtp服务器 s.login(mail_user,mail_pass) #登陆服务器 s.sendmail(me, to_list, msg.as_string()) #发送邮件 s.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五义</a>"): print "发送成功" else: print "发送失败"
3、发送带附件的邮件
发送带附件的邮件,首先要创建MIMEMultipart()实例,然后构造附件,如果有多个附件,可依次构造,最后利用smtplib.smtp发送。
# -*- coding: cp936 -*- ''' 发送带附件邮件 ''' from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib #创建一个带附件的实例 msg = MIMEMultipart() #构造附件1 att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename="123.doc"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字 msg.attach(att1) #构造附件2 att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename="123.txt"' msg.attach(att2) #加邮件头 msg['to'] = 'YYY@YYY.com' msg['from'] = 'XXX@XXX.com' msg['subject'] = 'hello world' #发送邮件 try: server = smtplib.SMTP() server.connect('smtp.XXX.com') server.login('XXX','XXXXX')#XXX为用户名,XXXXX为密码 server.sendmail(msg['from'], msg['to'],msg.as_string()) server.quit() print '发送成功' except Exception, e: print str(e)
4、利用MIMEimage发送图片
# -*- coding: cp936 -*- import smtplib import mimetypes from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage def AutoSendMail(): msg = MIMEMultipart() msg['From'] = "XXX@XXX.com" msg['To'] = "YYY@YYY.com" msg['Subject'] = "hello world" txt = MIMEText("这是中文的邮件内容哦",'plain','gb2312') msg.attach(txt) file1 = "C:\\hello.jpg" image = MIMEImage(open(file1,'rb').read()) image.add_header('Content-ID','<image1>') msg.attach(image) server = smtplib.SMTP() server.connect('smtp.XXX.com') server.login('XXX','XXXXXX') server.sendmail(msg['From'],msg['To'],msg.as_string()) server.quit() if __name__ == "__main__": AutoSendMail()
利用MIMEimage发送图片,原本是想图片能够在正文中显示,可是代码运行后发现,依然是以附件形式发送的,希望有高手能够指点一下,如何可以发送在正文中显示的图片的邮件,就是图片是附件中存在,但同时能显示在正文中,具体形式如下图。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。
更多详解python发送各类邮件的主要方法相关文章请关注PHP中文网!