【问题标题】:Bash to python convertion for sending email用于发送电子邮件的 Bash 到 python 转换
【发布时间】:2018-05-29 04:44:28
【问题描述】:

我正在将一个 shell 脚本转换为 python。在我的 python 代码中,当我尝试发送电子邮件时,我收到错误消息。我是 python 新手。请帮我解决这个问题。

外壳代码:

id=`whoami`

userid_list=2nd_user

SUBJECT=mail

echo "Content-Type: text/html; charset=iso-8859-1

      Content-Transfer-Encoding: 7bit

From: $id

To: $userid_list

Subject: $SUBJECT
" > $email

SENDMAIL=/usr/lib/sendmail

$SENDMAIL -oi -t < $email

python 代码:

sender_id = getpass.getuser()

userid = getpass.getuser()

content  = """Content-Type: text/html; charset=iso-8859-1

            Content-Transfer-Encoding: 7bit

            From: """ + sender__id + """

            To: """ + userid + """

            Subject: mail"""

email= "/tmp/mail"

with open(email, 'a') as f:

    f.write(content)

SENDMAIL = "/usr/lib/sendmail"

subprocess.call(SENDMAIL + " -oi -t < " + email, shell=True)

错误信息:

sendmail: fatal: vijay(1254164854): 在邮件头中找不到收件人地址

【问题讨论】:

  • 在 shell 代码中,使用相同的用户(发件人和收件人邮件 ID),它可以正常工作
  • 我希望这只是一个错字,但是您的内容变量中的sender__id 有两个下划线,而不是原来声明的sender_id 只有一个。
  • @James Joyce Alano。是的,它奏效了。感谢您的帮助
  • 你能检查一下它在/tmp/mail 中写的内容吗?也许这可能是一个提示。
  • @Learner 很高兴能提供帮助。我可以将其发布为官方答案吗?

标签: bash python-2.7 email subprocess


【解决方案1】:

您的内容变量中的sender__id 有两个下划线,而不是原来声明的sender_id 只有一个。

Python 将每个变量视为一个对象,并且每个变量都不需要声明即可使用,因此编译器/解释器在遇到诸如您发布的情况时不会警告您。

【讨论】:

    【解决方案2】:

    两个邮件文件(1 个来自 shell 和 1 个来自 python)的行对齐方式不同。当我更改对齐方式时,它起作用了。

    来自 shell 的电子邮件文件:

    内容类型:文本/html;字符集=iso-8859-1

                       Content-Transfer-Encoding: 7bit
    

    发件人:vijay

    致:库马尔

    主题:测试邮件

    来自 python 的电子邮件文件(“/tmp/mail”):

    内容类型:文本/html;字符集=iso-8859-1

                       Content-Transfer-Encoding: 7bit
                       From: vijay
                       To:  kumar
                       Subject: test mail
    

    我将电子邮件文件(从 python 代码生成)的对齐方式更改为 shell。它起作用了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 2019-10-18
      相关资源
      最近更新 更多