[R-br] Mandar email pelo R

Pedro Emmanuel Alvarenga Americano do Brasil emmanuel.brasil em gmail.com
Segunda Março 11 10:23:40 BRT 2013


Amigos de R,

Sei que essa questão volta algumas vezes na lista mas estou empacado. Estou
fazendo um data management de um projeto em que consiste em repetidas
vezes, tipo toda semana, verificar quantos voluntários entraram no proejto,
dados inconsistentes, dados ausentes e coisas assim. Então, eu consegui
fazer um script para esse fim em que gera um arquivo com algumas tabelas e
graficos.

Agora eu gostaria de incluir nesse script o envio de um email pra mim mesmo
com esse arquivo, para que eu possa verificar e depois encaminhar para os
outros participantes. Sei que existe o sendmailR, mas não estou conseguindo
fazer funcionar. Encontrei um catatau de gente referindo o mesmo erro em
diversos diferentes foruns:

> sendmail(from, to, subject, body,control=list(smtpServer="
ASPMX.L.GOOGLE.COM"))
Erro em socketConnection(host = server, port = port, blocking = TRUE) :
  não é possível abrir a conexão
Além disso: Mensagens de aviso perdidas:
In socketConnection(host = server, port = port, blocking = TRUE) :
  ASPMX.L.GOOGLE.COM:25 cannot be opened


Depois, consegui encontrar essa função em um dos foruns. O autor fala que
funciona, mas comigo tem dado um erro de conectividade e eu não sabendo
como dar a volta nesse erro. Será que tem alguma relação com o proxy?

> 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" = "
recip em somewhere.net") 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")
}

from <- list("Recipient" = "emmanuel.brasil em gmail.com")
to <- list("Recipient" = "emmanuel.brasil em gmail.com")
subject <- paste0("Pendencias Nomograma de ",Sys.time())
message <- "Mensagem automática com relatório de pendências do projeto
Nomograma."
attachment <- 'c:/banco/nomograma/Controle_recrutamento.doc'
> send.email(to,from,subject,message,attachment,'emmanuel.brasil em gmail.com
','...',confirmBeforeSend=FALSE)
Erro em jython.exec(rJython, mail) : (62, 'Connection refused')

Qualquer luz é bem vinda.

Abraço forte,

Dr. Pedro Emmanuel A. A. do Brasil
Curriculum Lattes:  http://lattes.cnpq.br/6597654894290806
Instituto de Pesquisa Clínica Evandro Chagas
Fundação Oswaldo Cruz
Rio de Janeiro - Brasil
Av. Brasil 4365,
CEP 21040-360,
Tel 55 21 3865-9648
email: pedro.brasil em ipec.fiocruz.br
email: emmanuel.brasil em gmail.com

---Apoio aos softwares livres
www.zotero.org - gerenciamento de referências bibliográficas.
www.broffice.org ou www.libreoffice.org - textos, planilhas ou
apresentações.
www.epidata.dk - entrada de dados.
www.r-project.org - análise de dados.
www.ubuntu.com - sistema operacional
-------------- Próxima Parte ----------
Um anexo em HTML foi limpo...
URL: <http://listas.inf.ufpr.br/pipermail/r-br/attachments/20130311/f13909af/attachment.html>


Mais detalhes sobre a lista de discussão R-br