r email smtp email-attachments

sendmailR(Parte 2): envío de archivos como archivos adjuntos de correo



email smtp (5)

Con el paquete mailR ( https://github.com/rpremraj/mailR ), puede enviar correos electrónicos HTML y adjuntar archivos con la siguiente facilidad:

send.mail(from = "[email protected]", to = c("[email protected]", "[email protected]"), subject = "Subject of the email", body = "<html>The apache logo - <img src=/"http://www.apache.org/images/asf_logo_wide.gif/"></html>", html = TRUE, smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE), attach.files = c("./download.log", "upload.log"), authenticate = TRUE, send = TRUE)

Editar (2014-05-13):

mailR se ha actualizado para permitir diferentes codificaciones de caracteres. A continuación se muestra un ejemplo para enviar el mensaje como UTF-8.

send.mail(from = "Sender Name <[email protected]>", to = "[email protected]", subject = "A quote from Gandhi", body = "In Hindi : थोडा सा अभ्यास बहुत सारे उपदेशों से बेहतर है। English translation: An ounce of practice is worth more than tons of preaching.", encoding = "utf-8", smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = T), authenticate = TRUE, send = TRUE)

Siguiendo las instrucciones proporcionadas en this pregunta relacionada, pude enviar mensajes de correo electrónico con formato html. Ahora la pregunta es esta: ¿Cómo debo modificar el siguiente código para adjuntar uno o más archivos (de cualquier tipo) a este mensaje?

library(sendmailR) from <- "<[email protected]>" to <- c("<[email protected]>","<[email protected]>") subject <- iconv("Message Title", to = "utf8") msg <- "<hr size=''2'' width=''33%'' style=''text-align: left;''><font size=''2''> <i>This email was sent automatically using <a href=''http://finzi.psych.upenn.edu/R/library/sendmailR/html/00Index.html'' rel=''nofollow'' target=''_blank''>sendmailR</a>.<br> Please do not reply directly to this e-mail.</i></font>" msg <- iconv(msg, to = "utf8") sapply(to,function(x) sendmail(from, x, subject, msg, control=list(smtpServer="###.###.###.###"), headers=list("Content-Type"="text/html; charset=UTF-8; format=flowed")))


Este es un ejemplo que se configura para un trabajo por lotes diario, como la configuración mediante sendmail () en R (disponible con el paquete sendmailR) con varios archivos adjuntos (un archivo CSV, un PDF):

Configuración de la información de fecha para hacer referencia en los nombres de archivo

> yesterday_date_stuff <- new.env() > yesterday_date_stuff[[''month'']] <- strftime(Sys.Date()-1, format="%m") > yesterday_date_stuff[[''day'']] <- strftime(Sys.Date()-1, format="%d") > yesterday_date_stuff[[''year'']] <- strftime(Sys.Date()-1, format="%y") > yesterday_date_stuff$month [1] "03" > yesterday_date_stuff$day [1] "29" > yesterday_date_stuff$year [1] "17"

Ahora cree parte de la información necesaria para la función sendmail () al final de esta publicación:

> from <- "[email protected]" > to <- c("[email protected]", "[email protected]", "[email protected]") > subject <- paste("whatever you want subject line to read for batch job analyzing data for ", yesterday_date_stuff$month, "/", yesterday_date_stuff$day, "/", yesterday_date_stuff$year, sep="") > body <- "Text to insert into the body of your email"

Especifique el servidor de correo aquí:

> mailControl=list(smtpServer="mail.whateveryourmailserveris.com")

Defina la ruta y el nombre del archivo adjunto 1:

> attachmentPath1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="") > attachmentName1 <- paste("file1name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".csv", sep="")

Definir objeto adjunto 1:

> attachmentObject1 <- mime_part(x=attachmentPath1,name=attachmentName1)

Defina la ruta y el nombre del archivo adjunto 2:

> attachmentPath2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="") > attachmentName2 <- paste("file2name", "_", yesterday_date_stuff$month, yesterday_date_stuff$day, yesterday_date_stuff$year, ".pdf", sep="")

Definir objeto adjunto 2:

> attachmentObject2 <- mime_part(x=attachmentPath2,name=attachmentName2)

Ahora combina el cuerpo del correo electrónico con tus archivos adjuntos:

> bodyWithAttachment <- list(body,attachmentObject1, attachmentObject2) > bodyWithAttachment [[1]] [1] "Text to insert into the body of your email" [[2]] <environment: 0x000000004efff188> attr(,"class") [1] "mime_part" [[3]] <environment: 0x00000000407a1b68> attr(,"class") [1] "mime_part"

Envía el correo electrónico usando la función sendmail ():

> sendmail(from=from, to=to, subject=subject, msg=bodyWithAttachment, control=mailControl)


Me gustaría dejar de usar R para esto. Existen soluciones estables, multiplataforma y de trabajo para hacer esto en Python, y puede llamar a Python desde R.

Si tuviera que ajustar un modelo de efectos mixtos en un programa de Python, llamaría R para hacerlo. Si quiero hacer una tarea de sistemas como enviar un correo electrónico en R, llamaré a Python para hacerlo. Vale la pena aprender si aún no lo sabes.


Tenga en cuenta que las versiones actuales de sendmailR admiten archivos adjuntos fuera de la caja haciendo que msg una lista de objetos mime_type , es decir, ahora

sendmail( from,to,subject, msg=list(mime_part("Here''s an attachment for you!"), mime_part(attachmentFileName)), control, headers)`


Una función de trabajo (al menos para mí):

sendMessage<-function(contents,subject,from,to,attMIME,attachment,control){ msg<-list(contents,sendmailR:::.file_attachment(attachment,attachment,attMIME)); sendmail(from=from,to=to,subject=subject,msg=msg,control=control); }

Se puede utilizar de esta manera:

png(''a.png'');hist(rnorm(700));dev.off() sendMessage(''Here you have a nice histogram:'', ''Nice picture'', ''[email protected]'', ''[email protected]'', ''image/png'', ''a.png'',list(smtpServer="..."))

Tenga en cuenta que el mensaje enviado por este ejemplo probablemente se marcará como correo no deseado, ya que es un texto breve y una imagen grande; sin embargo, para los mensajes más grandes y, digamos, los archivos adjuntos en pdf deben pasar. Si no, puede considerar agregar también una versión de texto del mensaje.

EDITAR (menos relevante ahora): la información más profunda sobre cómo hacer mensajes MIME puede encontrarse here .