如何通过“邮件”在Linux服务器上用Python发送邮件?

时间:2018-05-30 15:01:07

标签: python-2.7 email server

我正在尝试在Linux服务器上从python发送事件触发器上的邮件。服务器已安装邮件,我的代码如下:

import subprocess
subprocess.call(["mail","-s Hello there", "someone@gmail.com < 
this_text_document.txt"])

感觉好像我在这里像蝙蝠一样失明。接收永久装载。在中断时收到:“没有指定收件人 ...邮件未发送“ 请发送帮助。

2 个答案:

答案 0 :(得分:0)

您可以使用smtplib发送电子邮件,但您也需要SMTP服务器和MIMEText ::

import smtplib
from email.mime.text import MIMEText
from email.header import Header

server = smtplib.SMTP("smtp.server.com", 587)#port

server.ehlo()
server.starttls()
server.login('email@email.com', 'password')
body = 'Hello there'
msg = MIMEText(body,'plain','utf-8')
subject = 'Email test'
msg["Subject"] = Header(subject, 'utf-8')
from = 'email@email.com'
to = 'someone@gmail.com'
msg["From"] = Header(from, 'utf-8')
msg["To"] = Header(to, 'utf-8')
txt = msg.as_string()
server.sendmail(from, to, txt)

对于你的问题,你可以这样做:

import subprocess

subprocess.call('mail -s "Hello there" "someone@gmail.com" < this_text_document.txt"', shell=True)

谢谢!

答案 1 :(得分:0)

这将起作用:

def SendMail(Subject: str, Body: str):
    body_str_encoded_to_byte = Body.encode()
    return_stat = subprocess.run([f"mail", f"-s {Subject}", "Idan@mail.com"], input=body_str_encoded_to_byte)
    print(return_stat)