Translate

Wednesday, 27 November 2013

'sendmailR'

This package allows user to send emails from R which can be useful if you are running a task that takes a long time and need R to notify you when the job is completed. Also, this can be a simple way of distributing outputs of analytical models to intended recipients, when the model is automatically scheduled to run specific tasks on a regular basis. This is especially useful if the model is in the testing phase (or in proof of concept mode) prior to an operationalisation, and the business is yet to invest in proper infrastructure to fully integrate the model into business processes.

The below is the code used for activating sendmailR package and setting up smtp server.
install.packages("sendmailR",repos="http://cran.r-project.org")
library(sendmailR)

Server<-list(smtpServer="ASPMX.L.GOOGLE.COM")
It should be noted that the server used in the example, ASPMX.L.GOOGLE.COM, is a gmail server that does not require authentication. This will generate emails from the server hence there is a chance that this can be categorised by the recipient as a spam, or even be blocked from sending it depending on your computer's security settings.

If you are working from a secure network (e.g. at a work place) that is synchronised with the email system, smtp server should be changed to the synchronised email system, then you should not have issues associated with using ASPMX.L.GOOGLE.COM.

The below is the code for sending an email to a single recipient.
Sender <- sprintf("email address of sender","name of sender (optional)")
Subj <- "subject of email"
Email <- "contents/body of email"
Recipient<-sprintf("email address of recipient")

sendmail(from=Sender,to=Recipient,subject=Subj,msg=Email,control=Server)
With the email addresses, you may need to use "<" & ">" at the beginning and end of the email address respectively (e.g. "<abc@gmail.com>")

The below is the code for sending an email to multiple recipients.
Recipients<-sprintf(c("email address1","email address 2"))

sapply(Recipients,function(x)sendmail(from=Sender,to=x,subject=Subj,msg=Email,control=Server))
The below is the code for sending an email with attachments. The below example have two attachments. You need to specify the paths to the location in the drive where the attachments are saved in.
Email <- "contents/body of email"
Doc1<-"C:/.../ABC.PNG"
Object1<-mime_part(Doc1,name="ABC.PNG")
Doc2<-"C:/.../XXX.csv"
Object2<-mime_part(Doc2,name="XXX.csv")
Email_Att<- list(Email,Object1,Object2)

sapply(Recipients,function(x)sendmail(from=Sender,to=x,subject=Subj,msg=Email_Att,control=Server))






No comments:

Post a Comment