如何从数据库发送电子邮件
问题描述
我已使用Send email from Databricks Notebook with attachment中的代码尝试从我的Databricks社区版发送代码:
我使用了以下代码:
import smtplib
from pathlib import Path
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
from_email = "myname@myemail.co.uk"
to_email = "myname@myemail.co.uk"
def send_mail(send_from = from_email, send_to = to_email, subject = "Test", message = "Test", files=["/FileStore/tables2/"],
server="smtp.hosts.co.uk", port=587, username='myusername.co.uk', password='!L3qGWGuyw',
use_tls=True):
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(message))
for path in files:
part = MIMEBase('application', "octet-stream")
with open(path, 'rb') as file:
part.set_payload(file.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
'attachment; filename="{}"'.format(Path(path).name))
msg.attach(part)
smtp = smtplib.SMTP(server, port)
if use_tls:
smtp.starttls()
smtp.login(username, password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.quit()
如您所见,代码几乎完全相同。但是,当我运行代码时,我得到以下错误:
FileNotFoundError: [Errno 2] No such file or directory: '/FileStore/tables2/'
此错误是否也是因为我运行的是数据库社区版,就像上一个问题中的情况一样。
解决方案
/FileStore/tables2/
只是要作为附件发送的文件的名称。您需要在那里输入您的文件名,或者如果您不想发送附件,请将列表设置为空。它应该是本地文件,因此在Azure上使用/dbfs/....
,在社区版上-使用dbutils.fs.cp to copy file from DBFS to local file system。
相关文章