Sending mail via sendmail from python

前端 未结 8 1630
时光说笑
时光说笑 2020-12-04 12:04

If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?

Better yet, is there a good library that

8条回答
  •  粉色の甜心
    2020-12-04 12:19

    Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the email package, construct the mail with that, serialise it, and send it to /usr/sbin/sendmail using the subprocess module:

    import sys
    from email.mime.text import MIMEText
    from subprocess import Popen, PIPE
    
    
    msg = MIMEText("Here is the body of my message")
    msg["From"] = "me@example.com"
    msg["To"] = "you@example.com"
    msg["Subject"] = "This is the subject."
    p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
    # Both Python 2.X and 3.X
    p.communicate(msg.as_bytes() if sys.version_info >= (3,0) else msg.as_string()) 
    
    # Python 2.X
    p.communicate(msg.as_string())
    
    # Python 3.X
    p.communicate(msg.as_bytes())
    

提交回复
热议问题