Monday, June 13, 2011

Generating email from ASP.NET which opens in Outlook

My friend recently ran into a strange requirement from his client.

There is a gird on the webpage and user want a button which will extract data from grid into the excel sheet and create an email attach excel sheet to that email and provides a pop up box that will open the email in outlook which user can edit , add email address and send it to any one he desire.

Following code spinet can be used for achieving it (with an exception that user will have to open and forward the email)

Add a ASP.Net button to the page and paste the code in click event.



Dim OutLookEmailDirectory As String = "d:\test\OutlookEmail\email\"

Dim DirName As String 'New System.Guid

'' getting a temp guid which will be used for creating a temp directory.
'' This temp directory is required as we don;t the name of the file with which the SMTP will save email to.
Dim g As New System.Guid
DirName = System.Guid.NewGuid.ToString.Replace("-", "_")

'Create the temp Directory
If Not System.IO.Directory.Exists(OutLookEmailDirectory & DirName) Then
System.IO.Directory.CreateDirectory(OutLookEmailDirectory & DirName)
End If

'Create Mail message object
Dim x As New System.Net.Mail.MailMessage

x.To.Add("youremail@domain.com")
x.Subject = "testing"
x.Body = "testing"

Dim a As New System.Net.Mail.MailAddress("youremail@domain.com")
x.From = a


''Specify the path of file.
''Please modify this to suit your needs
Dim y As New System.Net.Mail.Attachment("c:\outlooktest.xlsx")

''Add the attachment to the email
x.Attachments.Add(y)


'' Create email object and specify the deliver method as pickup directory
Dim m As New System.Net.Mail.SmtpClient
m.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory
m.PickupDirectoryLocation = OutLookEmailDirectory & DirName '"c:\email"
m.Send(x)


'' get the name of email file from the temp directory.
'' As this is a temp directory we have created, we will have only one file which can be
Dim objDir As New System.IO.DirectoryInfo(OutLookEmailDirectory & DirName)
Dim GeneratedEmailName As String = String.Empty
For Each Str As System.IO.FileInfo In objDir.GetFiles("*.eml")
GeneratedEmailName = Str.Name
Exit For
Next

''Move the email to the temp directory of your choice, (probably same where you have generated the attachments.
'' Moving to directory where clean up operation is done at later stage
If System.IO.File.Exists(OutLookEmailDirectory & DirName & "\" & GeneratedEmailName) Then
System.IO.File.Move(OutLookEmailDirectory & DirName & "\" & GeneratedEmailName, OutLookEmailDirectory & GeneratedEmailName)
'GeneratedEmailName = OutLookEmailDirectory & "\" & GeneratedEmailName
End If

'' Delete the previously crated temp directory
If System.IO.Directory.Exists(OutLookEmailDirectory & DirName) Then
System.IO.Directory.Delete(OutLookEmailDirectory & DirName)
End If

'' Show the pop up box to use in order to open the email in outlook.
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=" & GeneratedEmailName)
Response.WriteFile(OutLookEmailDirectory & GeneratedEmailName)

Response.[End]()







Dim DirName As String 'New System.Guid

'' getting a temp guid which will be used for creating a temp directory.
'' This temp directory is required as we don;t the name of the file with which the SMTP will save email to.
Dim g As New System.Guid
DirName = System.Guid.NewGuid.ToString.Replace("-", "_")

'Create the temp Directory
If Not System.IO.Directory.Exists("d:\test\OutlookEmail\email\" & DirName) Then
System.IO.Directory.CreateDirectory("d:\test\OutlookEmail\email\" & DirName)
End If

'Create Mail message object
Dim x As New System.Net.Mail.MailMessage

x.To.Add("deepti.pare@gmail.com")
x.Subject = "testing"
x.Body = "testing"

Dim a As New System.Net.Mail.MailAddress("deepti.pare@gmail.com")
x.From = a


''Specify the path of file.
''Please modify this to suit your needs
Dim y As New System.Net.Mail.Attachment("c:\outlooktest.xlsx")

''Add the attachment to the email
x.Attachments.Add(y)


'' Create email object and specify the deliver method as pickup directory
Dim m As New System.Net.Mail.SmtpClient
m.DeliveryMethod = Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory
m.PickupDirectoryLocation = "d:\test\OutlookEmail\email\" & DirName '"c:\email"
m.Send(x)


'' get the name of email file from the temp directory.
'' As this is a temp directory we have created, we will have only one file which can be
Dim objDir As New System.IO.DirectoryInfo("d:\test\OutlookEmail\email\" & DirName)
Dim GeneratedEmailName As String = String.Empty
For Each Str As System.IO.FileInfo In objDir.GetFiles("*.eml")
GeneratedEmailName = Str.Name
Exit For
Next

''Move the email to the temp directory of your choice, (probably same where you have generated the attachments.
'' Moving to directory where clean up operation is done at later stage
If System.IO.File.Exists("d:\test\OutlookEmail\email\" & DirName & "\" & GeneratedEmailName) Then
System.IO.File.Move("d:\test\OutlookEmail\email\" & DirName & "\" & GeneratedEmailName, "d:\test\OutlookEmail\email\" & GeneratedEmailName)
'GeneratedEmailName = "d:\test\OutlookEmail\email\" & "\" & GeneratedEmailName
End If

'' Delete the previously crated temp directory
If System.IO.Directory.Exists("d:\test\OutlookEmail\email\" & DirName) Then
System.IO.Directory.Delete("d:\test\OutlookEmail\email\" & DirName)
End If

'' Show the pop up box to use in order to open the email in outlook.
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=" & GeneratedEmailName)
Response.WriteFile("d:\test\OutlookEmail\email\" & GeneratedEmailName)

Response.[End]()



Thursday, April 23, 2009

TimeZone Problem

I am working on application which is based on Client/Server model. Earlier server components were deployed as MTS Components but now we have migrated it to WCF Services. It was working all right until the day we deployed our client application in different time zone and server in different timezone. So the date 2nd Dec 2001 12:00:00 (Pacafic) was getting transalated to 1st Dec 2001 09:00:00 on the server (The Ingenious MTS .. huh?). I think its is not property of MTS.. otherwise Microsoft must have give the settings to control it. 

Unfortunately there is not solution for it in MS Visual Studio 2003, but in VS 2005 and later version they have introduced a new property in in datetime datatype called as "SpecifyKind". You can set it to DateTimeKind.Unspecified and it will stop offsetting (adjusting) the date based on different timezone. 

You should set the kind of datetime/date datatype before sending it to server or clients. 

Following is an example:

dim dtDate as datetime
dtDate = DateTime.SpecifyKind(dtDate, DateTimeKind.Unspecified)

Same behavior is seen for datetime column also which can be nutralized using the following code

If ds IsNot Nothing Then
            If ds.Tables.Count > 0 Then
                For Each dt As DataTable In ds.Tables
                    For Each col As System.Data.DataColumn In dt.Columns
                        Try
                            If col.DataType.FullName.ToUpper = "SYSTEM.DATETIME" Then
                                'Unspecified will prevent the offset to happen based on timezones
                                col.DateTimeMode = DataSetDateTime.Unspecified
                            End If
                        Catch ex As Exception
                        End Try
                    Next
                Next
            End If
        End If

hope this will help.

Wednesday, May 14, 2008

My First Ever Blog Post

This is my first blog (and off course the first post :D) and I am hoping to stick to it till the end of my Journey on this reel world called earth. I never had any plans of starting this blog, neither would I have started it ever, if my friend was not seeking help from me. So, the story goes like…

I got a call from my friend who was expecting some help from me on Visual Basic application (VBA). As I have hands on experience on Programming/Automation of office application (Thanks to Mr. Craig, who had assigned me PowerPoint Add-in Project from which I have learned a lot about the ActiveX Exe, ActiveX Controls etc), so indeed I agreed to help him. So when we started working on his project, I pretty much forgot many things and it took me some time to recall it (ehh.. what a waste of time).

So I though of starting this blog and I will post my programming experiences here. This will off course help me and hopefully will benefit others. I am hoping that in near future, I will post some articles about my experiences with Microsoft PowerPoint Add-in.