用 python,在windows下可設工作排程,python當主程式,py檔當參數
在linux下可設crontab,不用sudo
import os
import smtplib
import sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
def sendMail(mailfrom="", mailto="", mailcc="", attachmentDIR="", ext=""):
msg = MIMEMultipart()
msg["From"] = mailfrom
msg["To"] = mailto
if(mailcc != ""):
msg["cc"] = f'{mailcc}'
msg["Subject"] = "測試信"
msg["Body"] = ""
html = """
<html>
<head></head>
<body>
<h3>測試信件,加附件</h3>
</body>
</html>
"""
part2 = MIMEText(html, 'html')
msg.attach(part2)
if os.path.exists(attachmentDIR):
for d, r, fs in os.walk(attachmentDIR):
# 把指定目錄下的檔案列舉
for afile in fs:
filename = os.path.join(d, afile)
fileext = filename.split(".")[-1].lower()
# 如果副檔名是我們要的,寄出
#你也可以不做此步,全寄
if ext == "" or fileext == ext.lower():
with open(filename, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=os.path.basename(filename)
)
part[
'Content-Disposition'] = f'attachment; filename="{os.path.basename(filename)}"'
msg.attach(part)
# 把檔案加入附件清單(請留意外寄限制)
try:
smtpObj = smtplib.SMTP('mail.yourcompany.com', 25) # 非SSL smtp
smtpObj.login("yourname", "yourpassword")
# 只能這樣寫死的,帳號密碼
smtpObj.send_message(msg)
smtpObj.quit()
except smtplib.SMTPException:
print(f"發生錯誤")
return
# 主程式進入點
if __name__ == '__main__':
sendMail(mailfrom="yourname@yourcompany.com",
mailto="hername@hercompany.com",
attachmentDIR="d:\\csvdata", ext="csv")
已測試可正常執行 免安裝outlook/live/thunderbird/foxmail客戶端,免瀏覽器
C# 也可以,但不知你要的是啥語言
至於用BAT批次檔寫,恕在下不懂(真的不想懂)
如是單一部 windows 機又有 outlook 而且是長開 outlook 的話便可用VB搭 windows 內的排程.但你沒提及你是要在那執行???
把下面程式部份用 notepad save 再改 file format 變成 vbs, 雙按已可執行.但如要定時發放,請自行在 windows 排程中加入定時運作功能
Dim fso
Set olApp = CreateObject("outlook.application")
Set olApt = olApp.CreateItem(olAppointmentItem)
Set myItem = olApp.CreateItem(0)
With myItem
.To = E-mail address
.Subject = "Testing"
Set fso= CreateObject("Scripting.FileSystemObject")
Set Folder = fso.getfolder("Z:\abc\1234\") '資料夾路徑
For Each file In Folder.Files
.Attachments.Add "Z:\abc\1234\" & file.name
next
.Body = "As per subject."
.Display '測試時可以看
.Send '測試完便不用 display, 直接send
End With
https://github.com/dbader/schedule
https://github.com/jasonlvhit/gocron
不用cron、windows排程器的方案。
請問是否有可用Google Apps Script編寫讓Gmail每日將Google Drive的某個資料夾的資料以壓縮檔的方式寄出呢?