天天看点

Python使用SMTP发送邮件 Python使用SMTP发送邮件

Python浣跨??MTP??????浠?/h1>

SMTP锛?Simple Mail Transfer Protocol锛??崇??????浠朵?杈???璁?,瀹???涓?缁??ㄤ??辨??板???扮?????板??浼?????浠剁??瑙???锛??卞???ユ?у?朵俊浠剁??涓?杞??瑰???

python??smtplib??渚?浜?涓?绉?寰??逛究????寰??????靛????浠躲??瀹?瀵?mtp??璁?杩?琛?浜?绠?????灏?瑁???

Python??寤?SMTP 瀵硅薄璇?娉?濡?涓?锛?

import smtplib

smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )      
???拌?存??锛?
  • host: SMTP ???″?ㄤ富?恒?? 浣???浠ユ??瀹?涓绘?虹??ip?板??????????濡?:w3cschool.cc锛?杩?涓??????????般??
  • port: 濡???浣???渚?浜? host ???? 浣???瑕???瀹? SMTP ???′娇?ㄧ??绔??e?凤?涓??????典?SMTP绔??e?蜂负25??
  • local_hostname: 濡???SMTP?ㄤ??????轰?锛?浣?????瑕???瀹????″?ㄥ?板??涓?localhost ?冲????
Python SMTP瀵硅薄浣跨??endmail?规???????浠讹?璇?娉?濡?涓?锛?
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]      
???拌?存??锛?
  • from_addr: ??浠跺???????板????
  • to_addrs: 瀛?绗?覆??琛????浠跺?????板????
  • msg: ????娑???
杩???瑕?娉ㄦ??涓?涓?绗?涓?涓????帮?msg??瀛?绗?覆锛?琛ㄧず??浠躲????浠??ラ????浠朵????辨??棰?锛???淇′汉锛??朵欢浜猴???浠跺??瀹癸???浠剁??????锛???????浠剁???跺??锛?瑕?娉ㄦ??msg???煎???杩?涓??煎?灏辨??smtp??璁?涓?瀹?涔????煎???

瀹?渚?

浠ヤ???涓?涓?浣跨??ython??????浠剁??????瀹?渚?锛?
#!/usr/bin/python

import smtplib

sender = '[email?protected]'
receivers = ['[email?protected]']

message = """From: From Person <[email?protected]>
To: To Person <[email?protected]>
Subject: SMTP e-mail test

This 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"      

浣跨??ython????HTML?煎?????浠?/h2>

Python????HTML?煎?????浠朵?????绾?????娑???????浠朵???涔?澶?灏辨??灏?MIMEText涓?_subtype璁剧疆涓?tml???蜂?浠g??濡?涓?锛?

import smtplib  
from email.mime.text import MIMEText  
mailto_list=["[email?protected]"] 
mail_host="smtp.XXX.com"  #璁剧疆???″??mail_user="XXX"    #?ㄦ?峰??
mail_pass="XXXX"   #?d护 
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')    #??寤轰?涓?瀹?渚?锛?杩???璁剧疆涓?tml?煎???浠?    msg['Subject'] = sub    #璁剧疆涓婚?
    msg['From'] = me  
    msg['To'] = ";".join(to_list)  
    try:  
        s = smtplib.SMTP()  
        s.connect(mail_host)  #杩???mtp???″??        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 "????澶辫触"        
????浣?涔???浠ュ?ㄦ???浣?涓???瀹?Content-type涓?ext/html,濡?涓?瀹?渚?:
#!/usr/bin/python

import smtplib

message = """From: From Person <[email?protected]>
To: To Person <[email?protected]>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
"""

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"
except SMTPException:
   print "Error: unable to send email"      

Python????甯???浠剁????浠?/h2>

????甯???浠剁????浠讹?棣???瑕???寤?IMEMultipart()瀹?渚?锛??跺????????浠讹?濡?????澶?涓???浠讹???渚?娆℃????锛??????╃??mtplib.smtp??????

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib

#??寤轰?涓?甯???浠剁??瀹?渚?
msg = MIMEMultipart()

#??????浠?
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)

#??????浠?
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'] = '[email?protected]'
msg['from'] = '[email?protected]'
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)       
浠ヤ?瀹?渚???瀹?浜?Content-type header 涓?multipart/mixed锛?骞跺????/tmp/test.txt ??????浠讹?
#!/usr/bin/python

import smtplib
import base64

filename = "/tmp/test.txt"

# 璇诲????浠跺??瀹瑰苟浣跨??base64 缂???
fo = open(filename, "rb")
filecontent = fo.read()
encodedcontent = base64.b64encode(filecontent)  # base64

sender = '[email?protected]'
reciever = '[email?protected]'

marker = "AUNIQUEMARKER"

body ="""
This is a test email to send an attachement.
"""
# 瀹?涔?澶撮?ㄤ俊??
part1 = """From: From Person <[email?protected]>
To: To Person <[email?protected]>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)

# 瀹?涔?娑????ㄤ?
part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)

# 瀹?涔???杩??ㄥ??
part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)
message = part1 + part2 + part3

try:
   smtpObj = smtplib.SMTP('localhost')
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"
except Exception:
   print "Error: unable to send email"