Question

En suivant les instructions fournies dans cette question liée , Je suis en mesure d'envoyer des messages électroniques formated html. Maintenant, la question est la suivante: Comment dois-je modifier le code suivant, afin d'attacher un ou plusieurs fichiers (de tout type) à ce message

library(sendmailR)

from <- "<sendmailR@myserver.mycompany.com>"
to <- c("<someone@mycompany.com>","<anotherone@mycompany.com>")
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")))
Était-ce utile?

La solution

Avec le paquet mailR ( https://github.com/rpremraj/mailR ), vous pouvez envoyer des e-mails HTML et plus joindre des fichiers avec facilité comme ci-dessous:

send.mail(from = "sender@gmail.com",
          to = c("recipient1@gmail.com", "recipient2@gmail.com"),
          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)

Modifier (13/05/2014):

mailR a été mis à jour pour permettre à différents codages de caractères. est un exemple ci-dessous pour envoyer le message au format UTF-8.

send.mail(from = "Sender Name <sender@gmail.com>",
          to = "recipient@gmail.com",
          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)

Autres conseils

A travail (du moins pour moi) fonction:

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);
}

Peut être utilisé comme ceci:

png('a.png');hist(rnorm(700));dev.off()
sendMessage('Here you have a nice histogram:',
'Nice picture',
'from@example.com',
'to@example.com',
'image/png',
'a.png',list(smtpServer="..."))

averti que message envoyé par cet exemple sera probablement marqué comme spam, car il est un court texte et une grande image - néanmoins pour les grands messages et, disons, les pièces jointes PDF, il devrait passer. Sinon, vous pouvez envisager d'ajouter une version texte du message.

EDIT (moins pertinent maintenant): La plus profonde sur la façon dont un aperçu de faire des messages MIME peut être trouvé ici .

Notez que les versions actuelles des pièces jointes de support de sendmailR de la boîte en faisant msg une liste d'objets mime_type, à savoir que vous voudrais maintenant

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

Je renoncer à l'utilisation R pour cela. Travailler, des solutions multi-plateformes, stables pour ce faire en Python exist, et vous pouvez appeler Python de R.

Si je devais adapter un modèle à effets mixtes dans un programme Python j'appelle R pour le faire - si je veux faire une tâche de systèmes comme envoyez un email à R Je vais appeler Python pour le faire. Il vaut la peine d'apprendre si vous ne connaissez pas encore.

Voici un exemple qui est configuré pour un traitement par lots par jour comme le réglage en utilisant sendmail () dans R (disponible avec le package sendmailR) avec plusieurs pièces jointes (un CSV, un PDF):

Configuration des informations de date de référence dans les noms de fichiers:

> 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"

Maintenant, créez une partie des informations nécessaires à la fonction sendmail () à la fin de ce post:

> from <- "youremail@whateveryourmailserveris.com"
> to <- c("person_A_to_send_email_to@whatever.com", "person_B_to_send_email_to@whatever.com", "person_C_to_send_email_to@whatever.com")
> 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"                     

Indiquez ici le serveur de messagerie:

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

Définir chemin de fixation 1 et le nom:

> 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="")

Définir une pièce jointe objet:

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

Définir accessoire 2 chemin et le nom:

> 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="")

Définir objet accessoire 2:

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

Maintenant combiner le corps de l'e-mail avec vos pièces jointes:

> 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"

Envoyer l'e-mail en utilisant la fonction sendmail ():

> sendmail(from=from, to=to, subject=subject, msg=bodyWithAttachment, control=mailControl)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top