1. 程式人生 > >python兩種發郵件的方式smtp和outlook

python兩種發郵件的方式smtp和outlook

smtp是直接呼叫163郵箱的smtp伺服器,需要在163郵箱中設定一下。outlook傳送就是python直接呼叫win32方式

呼叫程式outlook直接傳送郵件。

import win32com.client as win32
import xlrd
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
receivers = ['[email protected]']
mail.To = receivers[0]
mail.Subject ='test1'
workbook = xlrd.open_workbook('E:\\kpi excel\\00_summary.xls')
mySheet = workbook.sheet_by_index(0)

nrows = mySheet.nrows
content = []
for i in range(nrows):
    ss = mySheet.row_values(i)
    content.append(ss)
    print(content)
    Truecontent =str(content)

mail.Body = Truecontent
mail.Attachments.Add('E:\\kpi excel\\00_summary.xls')
mail.Send()


smtp傳送郵件

import smtplib
from email.mime.text import MIMEText
mail_host = 'smtp.163.com'
mail_user = '18298268658'
mail_pass = 'cat123'
sender = '[email protected]'
receivers = ['[email protected]']

message = MIMEText('content','plain','utf-8')
message['Subject'] = 'title'
message['From'] = sender
message['To'] = receivers[0]  

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host,25)
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(
        sender,receivers,message.as_string())
    smtpObj.quit() 
    print('success')
except smtplib.SMTPException as e:
    print('error',e)