sending emails with attachments (from gmail or corporation)

# This script gets the unique values from a column and sends an email
from Spotfire.Dxp.Application.Filters import CheckBoxFilter 
from System import IO, Net, DateTime
from System.Net import Mail, Mime
from System.Text import Encoding

#A) CONFIG THE SCRIPT OPTIONS
#A.1 Unique column values from table to export
myTable = Document.Data.Tables["A"]
myColumn = "Item"

#A.2 Email configuration 
#gmail settings    : smtp.gmail.com,  port:587 encription=True credentials=True)
#corporate settings: smtp.contoso.com,port:25  encription=False credentials=False)
SMTPClient = "smtp.gmail.com"
SMTPPort = 587
useEncription = True
useCredentials = True

fromEmail = "me@gmail.com"
toEmail ="someone@abc.com"
fromEmailUsr = fromEmail
fromEmailPwd = "secretpassword"
filename = "myAttachment" + DateTime.Now.ToString() + ".csv"
myMailSubject = "Unique Values from " + myTable.Name + "." + myColumn
myMailBody = "These are the " + myMailSubject + "sent by some Spotfire geek"

#B) EXTRACT DATA for attachment
#B.1 Get uniques from myTable
s="Magic Numbers\r\n" 
filt=Document.FilteringSchemes[0].Item[myTable].Item[myTable.Columns.Item[myColumn]].As[CheckBoxFilter]()
for value in filt.Values: s+=value


#B.2 encode results
ms = IO.MemoryStream(Encoding.UTF8.GetBytes(s))

#C) SEND MAIL
#C.1 go by a postcard or envelope
MyMailMessage = Mail.MailMessage()


#C.2 Prepare email
MyMailMessage.From = Mail.MailAddress(fromEmail)
MyMailMessage.To.Add(toEmail)
MyMailMessage.Subject = myMailSubject
MyMailMessage.Body = myMailBody
ct = Mime.ContentType(Mime.MediaTypeNames.Text.Plain); 
attach = Mail.Attachment(ms, ct) 
attach.ContentDisposition.FileName = filename 
MyMailMessage.Attachments.Add(attach)
Mail.Attachment(ms, ct)

#C.3 Go to the USPS post office (Create the SMTPClient object and specify the SMTP GMail server and port)
SMTPServer = Mail.SmtpClient(SMTPClient)
SMTPServer.Port = SMTPPort

#C.4 Drop the email in the USPS outbox with the appropiate postage
if useCredentials: SMTPServer.Credentials = Net.NetworkCredential(fromEmailUsr, fromEmailPwd)
SMTPServer.EnableSsl = useEncription
print "thanks for using USPS service"
SMTPServer.Send(MyMailMessage)


No comments: