本文我會使用gmail 郵箱做爲郵箱測試,lzcom321@gmail.com 是個人私人郵箱,你們也能夠對我發送,以幫助你們的郵箱自動化測試
原文地址請點擊這裏python
將電子郵件發送給適當的我的,首先要轉換爲PDF,而後再將此PD附加到電子郵件中,而後將全部電子郵件由python
自動化發送。django
開始這個自動化案例以前,你須要將如下模塊導入到demo
中canvas
# 建立PDF from io import BytesIO from reportlab.pdfgen import canvas from django.http import HttpResponse # 自動化電子郵件 import email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText
你可能不須要上面列出的每一個模塊,可是我推薦你仍是將其所有導入其中網絡
對於本文,我將編寫一個簡單的示例。我會使用 canvas
建立pdf文件,並添加一些個性化設置,例如背景色,字體和字體大小,一些文本字符串和圖像(圖表)session
# 建立pdf c = canvas.Canvas('automate_report.pdf') # 設置背景顏色(此顏色爲黃色,我不推薦) c.setFillColorRGB(1,1,0) # 選擇字體和字體大小 c.setFont('Helvetica', 30) # 建立兩個文本字符串並在頁面上設置位置 c.drawString(5, 660,'Missing data chart for Titanic Data') c.drawString(5, 630, 'Report generated by Python') # 添加圖像以肯定其位置,寬度和高度 c.drawImage('Survival.png', 5,90,480,400) # show頁面並保存它 c.showPage() c.save()
注意事項app
咱們已經生成了一個pdf文件,正等待經過網絡空間發送。測試
在咱們深刻研究代碼以前,你須要建立一個刻錄機電子郵件賬戶,以即可以在本身的電子郵件(而不是朋友的電子郵件)上測試該電子郵件。字體
# 將關鍵電子郵件方面分配給變量,以便未來進行編輯 subject = "Weekly Report" body = "This is an email with the desired report attached" sender_email = "lzcom321@gmail.com" receiver_email = "lzcom321@icloud.com" file = "automate_report.pdf" password = "abc123" # 建立電子郵件頭(發件人,收件人和主題) email = MIMEMultipart() email["From"] = sender_email email["To"] = receiver_email email["Subject"] = subject # 在郵件中添加正文和附件 email.attach(MIMEText(body, "plain")) attach_file = open(file, "rb") report = MIMEBase("application", "octate-stream") report.set_payload((attach_file).read()) encoders.encode_base64(report) #add report header with the file name report.add_header("Content-Decomposition", "attachment", filename = file) email.attach(report) # 建立用於發送郵件的SMTP會話 session = smtplib.SMTP('smtp.gmail.com', 587) session.starttls() #enable security session.login(sender_email, password) text = email.as_string() session.sendmail(sender_email, receiver_email, text) session.quit() print('已發送郵件')
如今,註釋應該能夠幫助你瞭解全部代碼的工做方式以及彼此之間的交互。做爲我的喜愛,我喜歡將一般在腳本中硬編碼的內容設置爲一個變量,以便在須要時更易於編輯。ui