将单个文件附加到电子邮件

发布于 2024-12-12 22:11:20 字数 1615 浏览 4 评论 0原文

请先原谅我。当我尝试研究这个问题时,我最终看到了我根本无法理解的代码。我有大约 3 个小时的 Python 经验,并且尝试的时间可能超出了我的能力范围。

问题很简单。我可以成功地从 R(我的分析软件)调用 Python 来发送电子邮件。添加消息、主题、发往和发自字段是我可以做的。我希望能够发送附件。如果我能只发送一个附件,生活就会很棒。

到目前为止我的代码是

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import email.utils

fromaddr = '[email protected]'
toaddrs  = '[email protected]'
msg = MIMEMultipart(MIMEText('This is the body of the e-mail'))
msg['From'] = email.utils.formataddr(('Benjamin Nutter', fromaddr))
msg['To'] = email.utils.formataddr(('Benjamin Nutter', toaddrs))
msg['Subject'] = 'Simple test message'
f = 'filename.pdf'
part=MIMEBase('application', 'octet-stream')
part.set_payload(open(f, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' %    os.path.basename(f))
msg.attach(part)

"username = 'user'
"password = 'pw'

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()

当我运行此代码时,我收到消息 预期字符串有效负载:[type 'list'](但使用 < not [)

我今天的自学能力已达到极限。我希望这对于比我更有经验的人来说是一个明显的解决方案。

我希望你们都度过愉快的一天。

Please forgive me up front. When I've tried to research this question I end up looking at code that I simply can't comprehend. I have about 3 hours of experience with Python and am probably attempting more than I can handle.

The problem is simple. I can successfully call Python from R (my analysis software) to send an e-mail. Adding the message, subject, to, and from fields I can do. I'd like to be able to send an attachment. Life would be great if I could send just one attachment.

The code I have thus far is

import smtplib
import os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import email.utils

fromaddr = '[email protected]'
toaddrs  = '[email protected]'
msg = MIMEMultipart(MIMEText('This is the body of the e-mail'))
msg['From'] = email.utils.formataddr(('Benjamin Nutter', fromaddr))
msg['To'] = email.utils.formataddr(('Benjamin Nutter', toaddrs))
msg['Subject'] = 'Simple test message'
f = 'filename.pdf'
part=MIMEBase('application', 'octet-stream')
part.set_payload(open(f, 'rb').read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' %    os.path.basename(f))
msg.attach(part)

"username = 'user'
"password = 'pw'

server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()

When I run this code, I get the message
string payload expected: [type 'list'] (but with < not [)

I'm at my limit for self-learning today. I'm hoping this is an obvious fix to someone more experienced than myself.

I hope you're all having a great day.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岛徒 2024-12-19 22:11:20

您可以尝试使用“邮件程序”,而不是尝试直接使用 SMTP。邮件程序可以在此处找到。

这是一些简单的代码,展示了它是如何工作的。

messages=[]
message = mailer.Message()
message.attach('filename.txt')
message.From = 'Cool guy <[email protected]>'
message.To = 'Random Dude <[email protected]>'
message.Cc = 'Cards Fan <[email protected]>'
message.Subject = 'Test Email'
message.body = 'Here is the body of the email.'
messages.append(message)

emailer = mailer.Mailer(smtphost.example.com)
emailer.send(messages)

我根据当地的一些例子拼凑了这个。上面链接的邮件程序页面还显示了其他示例。找到此代码后,我将所有其他 python 电子邮件代码转换为使用此包。

You might try using 'mailer' instead of trying to use SMTP directly. Mailer can be found here.

Here is some simple code that shows how it works.

messages=[]
message = mailer.Message()
message.attach('filename.txt')
message.From = 'Cool guy <[email protected]>'
message.To = 'Random Dude <[email protected]>'
message.Cc = 'Cards Fan <[email protected]>'
message.Subject = 'Test Email'
message.body = 'Here is the body of the email.'
messages.append(message)

emailer = mailer.Mailer(smtphost.example.com)
emailer.send(messages)

I cobbled this together from some examples I had locally. The mailer page linked above also shows other examples. Once I found this code, I converted all my other python email code to use this package.

审判长 2024-12-19 22:11:20

我知道回答我自己的问题是不好的形式,但它开始奇迹般地工作,没有任何变化。这是一种给我留下第一印象的方式,对吗?

不管怎样,我把它包装成一个 R 函数。这将从 gmail 发送,但我还没有尝试从其他帐户发送。我最感兴趣的是从 Outlook 发送,因为我将使用它从我的脚本中发送分析报告。当我输入雇主的 SMTP 服务器时,出现错误“服务器不支持 SMTP AUTH 扩展”。我怀疑我必须和我的技术支持人员一起解决这个问题。

由于 winDialog() 函数,这可能只适用于 Windows。但这是一个好的开始。

send.email <- function(to, from, subject, 
  message, attachment=NULL,
  username, password,
  server="smtp.gmail.com:587",
  confirmBeforeSend=TRUE){
  # to: a list object of length 1.  Using list("Recipient" = "[email protected]") will send the message to the address but 
  #     the name will appear instead of the address.
  # from: a list object of length 1.  Same behavior as 'to'
  # subject: Character(1) giving the subject line.
  # message: Character(1) giving the body of the message
  # attachment: Character(1) giving the location of the attachment
  # username: character(1) giving the username.  If missing and you are using Windows, R will prompt you for the username.
  # password: character(1) giving the password.  If missing and you are using Windows, R will prompt you for the password.
  # server: character(1) giving the smtp server.
  # confirmBeforeSend: Logical.  If True, a dialog box appears seeking confirmation before sending the e-mail.  This is to 
  #                    prevent me to send multiple updates to a collaborator while I am working interactively.  

  if (!is.list(to) | !is.list(from)) stop("'to' and 'from' must be lists")
  if (length(from) > 1) stop("'from' must have length 1")
  if (length(to) > 1) stop("'send.email' currently only supports one recipient e-mail address")
  if (length(attachment) > 1) stop("'send.email' can currently send only one attachment")
  if (length(message) > 1){ 
    stop("'message' must be of length 1")
    message <- paste(message, collapse="\\n\\n")
  }

  if (is.null(names(to))) names(to) <- to
  if (is.null(names(from))) names(from) <- from
  if (!is.null(attachment)) if (!file.exists(attachment)) stop(paste("'", attachment, "' does not exist!", sep=""))

  if (missing(username)) username <- winDialogString("Please enter your e-mail username", "")
  if (missing(password)) password <- winDialogString("Please enter your e-mail password", "")

  require(rJython)
  rJython <- rJython()

  rJython$exec("import smtplib")
  rJython$exec("import os")
  rJython$exec("from email.MIMEMultipart import MIMEMultipart")
  rJython$exec("from email.MIMEBase import MIMEBase")
  rJython$exec("from email.MIMEText import MIMEText")
  rJython$exec("from email.Utils import COMMASPACE, formatdate")
  rJython$exec("from email import Encoders")
  rJython$exec("import email.utils")

  mail<-c(
  #Email settings
  paste("fromaddr = '", from, "'", sep=""),
  paste("toaddrs  = '", to, "'", sep=""),
  "msg = MIMEMultipart()",
  paste("msg.attach(MIMEText('", message, "'))", sep=""),
  paste("msg['From'] = email.utils.formataddr(('", names(from), "', fromaddr))", sep=""),
  paste("msg['To'] = email.utils.formataddr(('", names(to), "', toaddrs))", sep=""), 
  paste("msg['Subject'] = '", subject, "'", sep=""))

  if (!is.null(attachment)){
    mail <- c(mail,
      paste("f = '", attachment, "'", sep=""),
     "part=MIMEBase('application', 'octet-stream')",
     "part.set_payload(open(f, 'rb').read())",
     "Encoders.encode_base64(part)",
     "part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f))",
     "msg.attach(part)")
  }

#SMTP server credentials
  mail <- c(mail, 
    paste("username = '", username, "'", sep=""),
    paste("password = '", password, "'", sep=""),

#Set SMTP server and send email, e.g., google mail SMTP server
    paste("server = smtplib.SMTP('", server, "')", sep=""),
    "server.ehlo()",
    "server.starttls()",
    "server.ehlo()",
    "server.login(username,password)",
    "server.sendmail(fromaddr, toaddrs, msg.as_string())",
    "server.quit()")

  message.details <- 
    paste("To:               ", names(to), " (", unlist(to), ")", "\n",
          "From:             ", names(from), " (", unlist(from), ")", "\n",
          "Using server:     ", server, "\n",
          "Subject:          ", subject, "\n",
          "With Attachments: ", attachment, "\n",
          "And the message:\n", message, "\n", sep="")

  if (confirmBeforeSend) 
   SEND <- winDialog("yesnocancel", paste("Are you sure you want to send this e-mail to ", unlist(to), "?", sep=""))
   else SEND <- "YES"

  if (SEND %in% "YES"){ 
    jython.exec(rJython,mail)
    cat(message.details)
  }
  else cat("E-mail Delivery was Canceled by the User")
}

I know it's bad form to answer my own question, but it started working miraculously with no changes. What a way to make my first impression, right?

Anyway, I wrapped it into an R function. This will send from gmail, but I haven't tried sending it from other accounts yet. I'm most interested in sending from Outlook, since I'd be using this to send analysis reports from within my scripts. When I entered my employer's SMTP server, it gave the error "SMTP AUTH extension not supported by server." I suspect I'll have to work this out with my tech support guys.

This will probably only work on Windows, thanks to the winDialog() functions. But it's a good start.

send.email <- function(to, from, subject, 
  message, attachment=NULL,
  username, password,
  server="smtp.gmail.com:587",
  confirmBeforeSend=TRUE){
  # to: a list object of length 1.  Using list("Recipient" = "[email protected]") will send the message to the address but 
  #     the name will appear instead of the address.
  # from: a list object of length 1.  Same behavior as 'to'
  # subject: Character(1) giving the subject line.
  # message: Character(1) giving the body of the message
  # attachment: Character(1) giving the location of the attachment
  # username: character(1) giving the username.  If missing and you are using Windows, R will prompt you for the username.
  # password: character(1) giving the password.  If missing and you are using Windows, R will prompt you for the password.
  # server: character(1) giving the smtp server.
  # confirmBeforeSend: Logical.  If True, a dialog box appears seeking confirmation before sending the e-mail.  This is to 
  #                    prevent me to send multiple updates to a collaborator while I am working interactively.  

  if (!is.list(to) | !is.list(from)) stop("'to' and 'from' must be lists")
  if (length(from) > 1) stop("'from' must have length 1")
  if (length(to) > 1) stop("'send.email' currently only supports one recipient e-mail address")
  if (length(attachment) > 1) stop("'send.email' can currently send only one attachment")
  if (length(message) > 1){ 
    stop("'message' must be of length 1")
    message <- paste(message, collapse="\\n\\n")
  }

  if (is.null(names(to))) names(to) <- to
  if (is.null(names(from))) names(from) <- from
  if (!is.null(attachment)) if (!file.exists(attachment)) stop(paste("'", attachment, "' does not exist!", sep=""))

  if (missing(username)) username <- winDialogString("Please enter your e-mail username", "")
  if (missing(password)) password <- winDialogString("Please enter your e-mail password", "")

  require(rJython)
  rJython <- rJython()

  rJython$exec("import smtplib")
  rJython$exec("import os")
  rJython$exec("from email.MIMEMultipart import MIMEMultipart")
  rJython$exec("from email.MIMEBase import MIMEBase")
  rJython$exec("from email.MIMEText import MIMEText")
  rJython$exec("from email.Utils import COMMASPACE, formatdate")
  rJython$exec("from email import Encoders")
  rJython$exec("import email.utils")

  mail<-c(
  #Email settings
  paste("fromaddr = '", from, "'", sep=""),
  paste("toaddrs  = '", to, "'", sep=""),
  "msg = MIMEMultipart()",
  paste("msg.attach(MIMEText('", message, "'))", sep=""),
  paste("msg['From'] = email.utils.formataddr(('", names(from), "', fromaddr))", sep=""),
  paste("msg['To'] = email.utils.formataddr(('", names(to), "', toaddrs))", sep=""), 
  paste("msg['Subject'] = '", subject, "'", sep=""))

  if (!is.null(attachment)){
    mail <- c(mail,
      paste("f = '", attachment, "'", sep=""),
     "part=MIMEBase('application', 'octet-stream')",
     "part.set_payload(open(f, 'rb').read())",
     "Encoders.encode_base64(part)",
     "part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(f))",
     "msg.attach(part)")
  }

#SMTP server credentials
  mail <- c(mail, 
    paste("username = '", username, "'", sep=""),
    paste("password = '", password, "'", sep=""),

#Set SMTP server and send email, e.g., google mail SMTP server
    paste("server = smtplib.SMTP('", server, "')", sep=""),
    "server.ehlo()",
    "server.starttls()",
    "server.ehlo()",
    "server.login(username,password)",
    "server.sendmail(fromaddr, toaddrs, msg.as_string())",
    "server.quit()")

  message.details <- 
    paste("To:               ", names(to), " (", unlist(to), ")", "\n",
          "From:             ", names(from), " (", unlist(from), ")", "\n",
          "Using server:     ", server, "\n",
          "Subject:          ", subject, "\n",
          "With Attachments: ", attachment, "\n",
          "And the message:\n", message, "\n", sep="")

  if (confirmBeforeSend) 
   SEND <- winDialog("yesnocancel", paste("Are you sure you want to send this e-mail to ", unlist(to), "?", sep=""))
   else SEND <- "YES"

  if (SEND %in% "YES"){ 
    jython.exec(rJython,mail)
    cat(message.details)
  }
  else cat("E-mail Delivery was Canceled by the User")
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文