osx – 从Bash shell脚本发送邮件

前端之家收集整理的这篇文章主要介绍了osx – 从Bash shell脚本发送邮件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我编写一个 Bash shell脚本为Mac发送电子邮件通知打开一个自动化应用程序发送电子邮件与默认邮件帐户在Mail.app。自动化应用程序还附加脚本已写入的文本文件。这个解决方案的问题是

>发送时在GUI中可见
>如果Mail不是当前应用程序,它会偷取焦点
>它依赖于Mail.app的帐户设置在将来有效

我想绕过这些缺点,我应该直接从脚本通过输入SMTP设置,地址发送到等直接在脚本中发送邮件。捕获是我想在多台计算机(10.5和10.6)上部署此脚本,而不启用计算机上的Postfix。是否可以在脚本中执行此操作,因此它将在基于Mac OS X 10.5的安装上运行。和10.6?

更新:我发现了sendmail的-bs选项,这似乎是我需要的,但我失去了如何指定设置。

另外,为了澄清,我想指定SMTP设置的原因是来自localhost的端口25通过Postfix发送的邮件将被大多数公司防火墙阻止,但是如果我指定服务器和备用端口我不会运行进入这个问题。

由于Mac OS X包含Python,因此请考虑使用Python脚本而不是Bash脚本。我没有测试发送部分,但它遵循 standard example

Python脚本

  1. # Settings
  2.  
  3. SMTP_SERVER = 'mail.myisp.com'
  4. SMTP_PORT = 25
  5. SMTP_USERNAME = 'myusername'
  6. SMTP_PASSWORD = '$uper$ecret'
  7. SMTP_FROM = 'sender@example.com'
  8. SMTP_TO = 'recipient@example.com'
  9.  
  10. TEXT_FILENAME = '/script/output/my_attachment.txt'
  11. MESSAGE = """This is the message
  12. to be sent to the client.
  13. """
  14.  
  15. # Now construct the message
  16. import smtplib,email
  17. from email import encoders
  18. import os
  19.  
  20. msg = email.MIMEMultipart.MIMEMultipart()
  21. body = email.MIMEText.MIMEText(MESSAGE)
  22. attachment = email.MIMEBase.MIMEBase('text','plain')
  23. attachment.set_payload(open(TEXT_FILENAME).read())
  24. attachment.add_header('Content-Disposition','attachment',filename=os.path.basename(TEXT_FILENAME))
  25. encoders.encode_base64(attachment)
  26. msg.attach(body)
  27. msg.attach(attachment)
  28. msg.add_header('From',SMTP_FROM)
  29. msg.add_header('To',SMTP_TO)
  30.  
  31. # Now send the message
  32. mailer = smtplib.SMTP(SMTP_SERVER,SMTP_PORT)
  33. # EDIT: mailer is already connected
  34. # mailer.connect()
  35. mailer.login(SMTP_USERNAME,SMTP_PASSWORD)
  36. mailer.sendmail(SMTP_FROM,[SMTP_TO],msg.as_string())
  37. mailer.close()

我希望这有帮助。

猜你在找的Bash相关文章