Wednesday, October 19, 2016

How to send email notification in SSIS package using Gmail SMTP Server

In many cases, email notification is mandatory for ETL development. However, most of the small business clients usually don’t have their own SMTP server, in this case you can use Gmail SMTP server. There are so many articles about this topic, but many of them having bugs in the code. Hope this would help to run bug free and easily understandable. Also this code works well in Azure virtual machines too.
Design SSIS job using with required parameters. In here, Email Body, Email Subject and Email To parameters/variables are used.
Create a Script task using below code, this code would help to send email with multiple recipients.
Actual C# Code:
public void Main()
{
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("uma@gmail.com", "*********");
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.From = new MailAddress("umashan@gmail.com");

string addresses = Dts.Variables["$Project::EmailTo"].Value.ToString();
foreach (var address in addresses.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries))
{
msg.To.Add(address);
}

msg.Subject = Dts.Variables["User::EmailSubject"].Value.ToString();
msg.Body = Dts.Variables["User::EmailBody"].Value.ToString();
smtp.Send(msg);

Dts.TaskResult = (int)ScriptResults.Success;
}

enum
ScriptResults
{ Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
Cheers!

Uma

5 comments:

  1. Interesting .. thanks ..

    I tried this ...

    I added these (to resolve unresolved object types ..) (maybe these are wrong?)

    using System.Net;
    using System.Net.Mail;
    I get an issue / error at run time ..
    Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.

    I will consider .. hmmm

    ReplyDelete
  2. This was my fault ..
    Yes - this now worked fine for me ..
    A related link is also this one:
    https://stackoverflow.com/questions/32260/sending-email-in-net-through-gmail
    Thanks ..

    ReplyDelete
  3. Can you tell me exactly what you did to fix the error? I am also getting the same error : Error: 0x1 at Script Task: Exception has been thrown by the target of an invocation.
    Thanks in advance

    ReplyDelete
    Replies
    1. Nevermind. Found what the issue was. Turns out I tried to use a Project Variable that doesnt exist instead of the Package Variable i created

      Delete
  4. I think SSIS is the best tool to solve problems and make more use of some tools of IT.

    SSIS Postgresql Write

    ReplyDelete