Python網路程式設計:E-mail服務(八) 實現抄送和密送功能
阿新 • • 發佈:2019-01-09
簡介
本文介紹如何通過smtp模組實現郵件的抄送和密送功能。抄送功能實現
在傳送郵件時,除了傳送給相關的責任人,有時還需要知會某些人。這時就需要在郵件裡指定抄送人員列表。相關實現如下:這裡需要注意的是,需要將所以傳送和抄送人員以列表的形式,傳送給sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])函式的to_addrs引數。否則CC功能失效。import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import os FROMADDR = "[email protected]" PASSWORD = 'foo' TOADDR = ['[email protected]', '[email protected]
'] CCADDR = ['[email protected]', '[email protected]'] # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = 'Test' msg['From'] = FROMADDR msg['To'] = ', '.join(TOADDR) msg['Cc'] = ', '.join(CCADDR) # Create the body of the message (an HTML version). text = """Hi this is the body """ # Record the MIME types of both parts - text/plain and text/html. body = MIMEText(text, 'plain') # Attach parts into message container. msg.attach(body) # Send the message via local SMTP server. s = smtplib.SMTP('server.com', 587) s.sendmail(FROMADDR, TOADDR + CCADDR, msg.as_string()) s.quit()
實現BCC功能
使用者如果需要實現密送(BCC)功能,和上面介紹的抄送功能類似。參考程式碼實現:oaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = ' [email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
+ "To: %s\r\n" % toaddr
+ "CC: %s\r\n" % ",".join(cc)
+ "Subject: %s\r\n" % message_subject
+ "\r\n"
+ message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('smtp.sunnydale.k12.ca.us')
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, message)
server.quit()