Send Exported PDF as Attachment in Email - vb.net

I am trying to send PDF as attachment in mail but I am struggling to find out what should be the path. I learned to Export Crystal Report in PDF Format but I dont know how to give the path in the attachment:
This is how I am Exporting PDF
Dim rptDocument As ReportDocument = New ReportDocument()
rptDocument.Load(mReportPath)
Dim exportOpts As ExportOptions = New ExportOptions()
Dim pdfOpts As PdfRtfWordFormatOptions = ExportOptions.CreatePdfRtfWordFormatOptions()
exportOpts.ExportFormatType = ExportFormatType.PortableDocFormat
exportOpts.ExportFormatOptions = pdfOpts
rptDocument.ExportToHttpResponse(exportOpts, Response, True, "")
And this is the code to send pdf via email:
Dim msg As New MailMessage()
msg.From = New MailAddress("proccoinvoice#gmail.com")
msg.[To].Add(recipient)
msg.Subject = "Procco Invoice"
msg.Body = "Invoice attached"
msg.Attachments.Add(New Attachment(filepath)) //Path should be given here
Dim client As New SmtpClient("smtp.gmail.com")
client.Port = 25
client.Credentials = New NetworkCredential("proccoinvoice#gmail.com", "<Procco>;1947")
client.EnableSsl = True
client.Send(msg)
My question is How do I give path of the PDF that is generated at runtime in the attachment?

You need to convert the PDF file into byte[] to send as a attachment in mail.
Please check below code.
byte[] pdfarry = null;
using (MemoryStream ms = new MemoryStream())
{
document.Save(ms, false);
document.Close();
pdfarry = ms.ToArray();
}
mailMessage.Attachments.Add(new Attachment(pdfarry, "testPDF.pdf", "application/pdf"));
smtpClient = new SmtpClient("xxxx");
smtpUserInfo = new System.Net.NetworkCredential("xxxx", "xxx", xxx");
smtpClient.Credentials = smtpUserInfo;
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(mailMessage);

Related

Getting wrong size of pdf file by mail

I am sending a pdf file size 278kb but I'm getting a file size 5 kb that I can't open... I don't understand where is the problem... this is my code :
MailMessage oMail = new MailMessage();
string base64String = "";
using (WebClient client = new WebClient())
{
var bytes = client.DownloadData(pdfUrl);
base64String = Convert.ToBase64String(bytes);
}
var fileName = FileName;
MemoryStream strm = new MemoryStream(Convert.FromBase64String(base64String));
Attachment data = new Attachment(strm, fileName);
oMail.Attachments.Add(data);
oMail.From = new MailAddress(from);
oMail.To.Add(new MailAddress(to));
oMail.Subject = subject;
oMail.Body = body;
SmtpClient oServer = new SmtpClient("XXX.XXX.XX.XXX");
oServer.Port = **;
oServer.EnableSsl = false;
oServer.Send(oMail);

adding a local pdf attachment to an email in microsoft crm with vb .net

I'm creating an email entity record and trying to download a pdf and attaching to the email using organizationService.
//orgNIZtionaervice to establish connection with crm
Dim service As IOrganizationService = Crm_GetOrganizationService()
Dim xrmContext As New CrmServiceContext(service)
Dim filepath = C:\Development\OpenWorks\owreports\PayAdviceAttachments
// webclient to download file and storing in local
Dim webclient As System.Net.WebClient = New System.Net.WebClient
webclient.UseDefaultCredentials = True
webclient.Credentials = New System.Net.NetworkCredential(My.Settings.WebClientUserName, My.Settings.WebClientPassword)
webclient.DownloadFile(uri, filePath)
// creating email
Dim email As New Email
email.RegardingObjectId = New EntityReference("account", x)
email.MimeType = "pdf"
email.Subject = "test"
email.To = New ActivityParty() {toParty}
**_emailId** = service.Create(email)
To attach an attachment I'm not sure how to attach the file from the local
Below is the code I tried but it is not working.
Dim attachList As List(Of ActivityMimeAttachment) = New List(Of ActivityMimeAttachment)
Dim attach As New ActivityMimeAttachment
attach.ObjectId = New EntityReference(email.EntityLogicalName, **_emailId**)
attach.ObjectTypeCode = email.EntityLogicalName
attach.FileName = filePath
attach.FileName = "test"
service.Create(attach)
any help on how to attach the downloaded pdf?

pdf arrives damaged on when I send it via email

I want to send a pdf file via email, the file arrives but it damaged, any idea why?
Dim buffer As Byte() = New Byte(6499) {}
Dim bytesRead As Integer = 0
bytesRead = file.FileByteStream.Read(buffer, 0, buffer.Length)
Dim ms As New MemoryStream(bytesRead)
ms.Seek(0, SeekOrigin.Begin)
mail.Attachments.Add(New Attachment(ms, "test.pdf", "application/pdf"))
mail.IsBodyHtml = False
mail.From = New System.Net.Mail.MailAddress("xxxxx#gmail.com")
mail.To.Add("yyyyyy#gmail.com")
mail.Subject = "test subject"
mail.Body = "test body"
mail.Priority = System.Net.Mail.MailPriority.Normal
Dim smtp As New System.Net.Mail.SmtpClient
smtp.Host = "smtp.gmail.com"
smtp.Credentials = New System.Net.NetworkCredential("mymail#gmail.com", "pass")
smtp.Port = 587
smtp.EnableSsl = True
smtp.Send(mail)enter code here
I'm not sure from your question if you're reading the attachment in from the file system, but try changing this line:
Dim ms As New MemoryStream(bytesRead)
to this:
Dim ms = File.OpenRead("my file path")
and discard everything above it.

How to send Image as email attachment using Restful service

Below is the vb.net code that i'm using to receive an image from jquery ajax call..
Public Function MailKpiChart(ByVal img As String) As GenericResponse(Of Boolean) Implements IKPI.MailKpiChart
Dim SmtpServer As New Net.Mail.SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential("xyz#gmail.com", "password")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
Dim blStatus As Boolean
Try
Dim mailMessage As New MailMessage()
mailMessage.From = New MailAddress("from#gmail.com", ".Net Devoloper")
mailMessage.To.Add(New MailAddress("to#gmail.com"))
mailMessage.Subject = "test mail"
mailMessage.Body = "hello world"
Dim imgStream As New MemoryStream()
Dim Image As System.Drawing.Bitmap = getImagefromBase64(img)
Dim filename As String = "sample image"
Image.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png)
mailMessage.Attachments.Add(New Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg))
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network
SmtpServer.Send(mailMessage)
blStatus = True
Return ServiceUtility.BuildResponse(Of Boolean)(blStatus, String.Empty, String.Empty, 0)
Catch ex As Exception
Return ServiceUtility.BuildResponse(Of Boolean)(False, "",
ex.Message, AppConstants.ErrorSeverityCodes.HIGH)
End Try
End Function
and this is the function where i'm converting base64 string to an image
Public Function getImagefromBase64(ByVal uploadedImage As String) As Image
'get a temp image from bytes, instead of loading from disk
'data:image/gif;base64,
'this image is a single pixel (black)
Dim bytes As Byte() = Convert.FromBase64String(uploadedImage)
Dim image__1 As Image
Using ms As New MemoryStream(bytes)
ms.Write(bytes, 0, bytes.Length)
image__1 = Image.FromStream(ms)
End Using
Return image__1
End Function
and when i see my gmail inbox i c a mail with an attachment but i dont see the actual image which i've sent..i just c a blank image
Help Needed
Regards
I had the same issue and solved it by just adding the following line just before attaching the stream to the message.
imgStream.Position = 0
Regards,
Jonathan.
add your url - points to another web site
Dim bodys As String = "<html><head><title> example </title></head><body><table width='100%'>"
bodys += "<p><img width=135 height=77 src='http://www.example.com/image.gif'></p>"
bodys += "</table></body></html>"
Dim mails As New System.Net.Mail.MailMessage()
SmtpServer.Host = "127.0.0.1"
SmtpServer.Port = 25
mails = New System.Net.Mail.MailMessage()
mails.From = New System.Net.Mail.MailAddress("example#example.com")
mails.To.Add(txtEmail.Text)
mails.Subject = ""
mails.BodyEncoding = Encoding.UTF8
mails.IsBodyHtml = True
mails.Body = bodys.ToString()
SmtpServer.Send(mails)
A relative URL - points to a file within a web site
src="image.gif"
http://www.w3schools.com/tags/att_img_src.asp

VB.net itextsharp attachment

i am trying to send PDF file using itextsharp , the email sends fine but with out the pdf attachment
can some tell me what is wrong with my code ?
here is my code :
Dim pdfFile As MemoryStream = New MemoryStream()
Dim d As Document = New Document(PageSize.A4, 60, 60, 40, 40)
Dim w As PdfWriter = PdfWriter.GetInstance(d, pdfFile)
w.Open()
w.Add(New Paragraph("do foo something "))
Dim message As New MailMessage()
message.From = New MailAddress("******")
message.To.Add(New MailAddress("***************"))
message.Subject = "new image "
message.Body = "this is the apak chart img"
Dim data As New Attachment(pdfFile, New System.Net.Mime.ContentType("application/pdf"))
message.Attachments.Add(data)
Dim client As New SmtpClient()
client.Host = "smtp.gmail.com"
client.Credentials = New NetworkCredential("*****", "*******")
client.EnableSsl = True
client.Port = 587
client.Send(message)
Try flushing the writer and rewinding the stream:
Dim pdfFile As MemoryStream = New MemoryStream()
Dim d As Document = New Document(PageSize.A4, 60, 60, 40, 40)
Dim w As PdfWriter = PdfWriter.GetInstance(d, pdfFile)
w.Open()
w.Add(New Paragraph("do foo something "))
w.CloseStream = false;
d.Close();
pdfFile.Position = 0;
Adapted from: iTextSharp - Sending in-memory pdf in an email attachment