I need to create a vb script in order to Send an Email with Attachments. I am having no luck creating a simple script to email me in test with no attachments. In My Package i Have Variables Assigned for the following: MailTo =
=email@example.com, SmtpServer = MyServer MailMessage = MailSubject = In My Script Task I have ReadOnlyVariables for MailTo, MailFrom, SmtpServer ReadWriteVariable = MailSubject (I will try the message after I get it to just email successfully Here is my script Imports System Imports
System.Net Imports System.Data Imports System.Net.Mail Imports System.Net.NetworkCredential Imports Microsoft.SqlServer.Dts.Runtime Public Class ScriptMain Public Sub Main() Dim str_To As String Dim str_From As String Dim str_Message As String Dim str_Subject As String Try 'Create Mail Message and Subject Dts.Variables("User::MailSubject").Value = "Status for Order: " Dts.Variables("User::MailMessage").Value = "The order number: placed on is ready for shipment. Please generate invoice for amount: " 'Read mail attributes from package variable into local variable str_To = Dts.Variables("MailTo").Value.ToString str_From = Dts.Variables("MailFrom").Value.ToString str_Message = Dts.Variables("MailMessage").Value.ToString str_Subject = Dts.Variables("MailSubject").Value.ToString 'Send Mail MailSend(str_To, str_From, str_Subject, str_Message) Catch ex As Exception End Try Dts.TaskResult = Dts.Results.Success End Sub Public Sub MailSend(ByVal ToMail As String, ByVal From As String, ByVal Subject As String, ByVal Message As String) Dim smtpclient As New SmtpClient Dim mailmessage As New MailMessage Dim fromadd As New MailAddress(From) 'SMTP server will be picked from cinfig file smtpclient.Host = Dts.Variables("SmtpServer").Value.ToString smtpclient.Port = 25 smtpclient.Credentials = CredentialCache.DefaultNetworkCredentials mailmessage.From = fromadd mailmessage.To.Add(ToMail) mailmessage.Subject = CStr(Subject) mailmessage.Body = CStr(Message) smtpclient.Send(mailmessage) End Sub End Class Can Someone please help? This shows green as successful but no error messages ever appear and no messages appear.
The code has some small problems. Here is what you can try to make it work: Add this line to the code to make sure that the message is sent in Html format mailmessage.IsBodyHtml = true Optionally set the priority: mailmessage.Priority = MailPriority.Normal If you need to add any attachments to it then use this: 'file path should be visible to the SQL Server mailmessage.Attachments.Add(new Attachment(filePath)) And finally, please consider wrapping your message into the using block to prevent memory leaks. MailMessage type implements IDisposable interface, and so any instance of it should be disposed promptly after use. Oleg