In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Most people don't understand the knowledge points of this article "How to use SMTP to send mail in Python", so Xiaobian summarizes the following contents for everyone. The contents are detailed, the steps are clear, and they have certain reference value. I hope everyone can gain something after reading this article. Let's take a look at this article "How to use SMTP to send mail in Python".
Python creates SMTP objects Syntax import smtplibsmtpObj = smtplib.SMTP( [host [, port [, local_hostname]] )
Parameter Description:
host: SMTP server host. You can specify the ip address or domain name of the host e.g. w3cschool.cc, this is optional.
port: If you provide the host parameter, you need to specify the port number used by the SMTP service, typically SMTP port number 25.
local_hostname: If SMTP is on your local machine, you only need to specify the server address as localhost.
Python SMTP objects use the sendmail method to send mail, with the following syntax:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
Parameter Description:
from_addr: Message sender address.
to_addrs: String list, address to send mail to.
msg: Send message
Note here the third parameter, msg, is a string representing mail. We know that mail is generally composed of title, sender, recipient, mail content, attachments, etc. When sending mail, pay attention to the msg format. This format is defined in the smtp protocol.
examples
Here is a simple example of sending mail using Python
#!/ usr/bin/pythonimport smtplibsender = 'from@fromdomain.com'receivers = ['to@todomain.com']message = """From: From PersonTo: To PersonSubject: SMTP e-mail testThis is a test e-mail message. """try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"
Send HTML mail using Python
Python sends HTML messages differently from plain text messages by setting the_subtype in MIMEText to html. The specific codes are as follows:
import smtplib from email.mime.text import MIMEText mailto_list=["YYY@YYY.com"]mail_host="smtp.XXX.com" #Set server mail_user="XXX" #username mail_pass="XXXX" #password mail_postfix="XXX.com" #suffix of outbox def send_mail(to_list,sub,content): #to_list: recipient;sub: subject;content: mail content me="hello"+"+mail_user+"@"+mail_postfix+">" #Hello here can be set arbitrarily. After receiving the letter, it will be displayed according to the settings. msg = MIMEText(content,_subtype='html',_charset='gb2312') #Create an instance, here set to html format mail msg['Subject'] = sub #Set theme msg['From'] = me msg['To'] = ";".join(to_list) try: s = smtplib.SMTP() s.connect(mail_host) #connect smtp server s.login(mail_user,mail_pass) #login server s.sendmail(me, to_list, msg.as_string()) #Send mail s.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail(mailto_list,"hello","small five righteousness"): print "Send successfully" else: print "Send failed"
Alternatively, you can specify the Content-type as text/html in the message body, as follows:
#!/ usr/bin/pythonimport smtplibmessage = """From: From PersonTo: To PersonMIME-Version: 1.0Content-type: text/htmlSubject: SMTP HTML e-mail testThis is an e-mail message to be sent in HTML formatThis is HTML message.This is headline. """try: smtpObj = smtplib.SMTP('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"
Python sends mail with attachments
To send mail with attachments, first create MIMEMultipart() instance, then construct attachments, if there are multiple attachments, you can construct them in turn, and finally use smtplib.smtp to send.
from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport smtplib#Create an instance with attachments msg = MIMEMultipart()#Construct attachments 1att1 = MIMEText (open('d:123.rar', 'rb').read(), 'base64', 'gb2312')att1["Content-Type"] = 'application/octet-stream'att1["Content-Disposition"] = 'attachment; filename="123.doc"'#filename here can be arbitrarily written, what name to write, what name to display in the email msg.attach(att1)#construct attachment 2att2 = 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)#Add header msg <$'to'] = 'Y@YY.com'msg <$'from '] = 'XXX@XXX.com'msg <$'subject'] = 'hello world'#Send email try: server = smtplib.SMTP() server.connect('smtp.XXX.com') server.login ('XXX ',' XXXX')#XXX is the username, XXXXX is the password server.sendmail(msg['from'], msg['to'],msg.as_string()) server.quit() print 'send successfully'except Exception, e: print str(e)
The following example specifies the Content-type header as multipart/mixed and sends the/tmp/test.txt text file:
#!/ usr/bin/pythonimport smtplibimport base64filename = "/tmp/test.txt"#Read the file contents and use base64 encoding fo = open(filename, "rb")filecontent = fo.read ()encodedcontent = base64.b64encode(filecontent) # base64sender = 'webmaster@tutorialpoint.com'reciever = 'amrood. gmail.com'marker = "AUNIQUEMARKER"body ="""This is a test email to send an attachment. """#Define header informationpart1 = """From: From PersonTo: To PersonSubject: Sending AttachmentMIME-Version: 1.0Content-Type: multipart/mixed; boundary=%s--%s"" %(marker, marker)#Define Message Action part2 = """Content-Type: text/plainContent-Transfer-Encoding:8bit%s--%s""" %(body,marker)#Define nearby part3 = """Content-Type: multipart/mixed; name="%s"Content-Transfer-Encoding:base64Content-Disposition: attachment; filename=%s%s--%s--""" %(filename, filename, encodedcontent, marker)message = part1 + part2 + part3try: smtpObj = smtplib.SMTP ('localhost') smtpObj.sendmail (sender, reciever, message) print "Successfully sent email"except Exception: print "Error: unable to send email"The above is about the content of this article" How to use SMTP to send mail in Python ". I believe everyone has a certain understanding. I hope the content shared by Xiaobian will help everyone. If you want to know more about relevant knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.