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);
Related
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);
I am using the G Drive REST endpoints (not .net client) to upload docx files through vb .net. My problem is that if even i declare the query parameter "convert" as true, the files are getting uploaded but they never auto-convert.
The first thing i do is to create a new file with POST and after that i upload the content with Put in the upload uri in a separate request.
it does not even work when i use the Google Playground to upload the docx files.
Public Shared Function UploadStream(fileStream As IO.Stream, filename As String, mimetype As String, target As String, accesstoken As String, Optional ConvertToGDoc As Boolean = False) As String
Try
Dim subject As String = ""
Dim doc As New Aspose.Words.Document
Dim docformat = Aspose.Words.FileFormatUtil.DetectFileFormat(fileStream) ' detect the format of the file Then 'check if the file is doc or docx
If docformat.LoadFormat = Aspose.Words.LoadFormat.Doc Or docformat.LoadFormat = Aspose.Words.LoadFormat.Docx Then 'check if the file is word document
doc = New Aspose.Words.Document(fileStream)
subject = doc.BuiltInDocumentProperties.Subject 'get the subject from the word file
If doc.BuiltInDocumentProperties.Subject = "" Then subject = "none"
Else
subject = "none" 'set the subject as none if the file is not word file
End If
Dim localmd5 = Files.MD5stream(fileStream)
Dim baseaddress = "https://www.googleapis.com/drive/v2/files?convert=" + ConvertToGDoc.ToString
Dim req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "POST"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
req.ContentType = "application/json"
Dim writer = New Newtonsoft.Json.Linq.JTokenWriter()
writer.WriteStartObject()
writer.WritePropertyName("title")
writer.WriteValue(filename)
writer.WritePropertyName("parents")
writer.WriteStartArray()
writer.WriteRawValue("{'id':'" + target + "'}")
writer.WriteEndArray()
writer.WritePropertyName("properties")
writer.WriteStartArray()
writer.WriteRawValue("{'key':'Subject','value':'" + subject + "'},{'key':'MD5','value':'" + localmd5 + "'},{'key':'Author','value':''}")
writer.WriteEndArray()
writer.WriteEndObject()
Dim bodybytes = Text.Encoding.UTF8.GetBytes(writer.Token.ToString)
req.ContentLength = bodybytes.Length
Dim requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
Dim resp As System.Net.HttpWebResponse = req.GetResponse()
Dim response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Dim json As Newtonsoft.Json.Linq.JObject
json = Newtonsoft.Json.Linq.JObject.Parse(response)
Dim fileId = json.SelectToken("id").ToString()
baseaddress = "https://www.googleapis.com/upload/drive/v2/files/" + fileId + "?uploadType=media&convert=" + ConvertToGDoc.ToString
req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "Put"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
bodybytes = General.GetStreamAsByteArray(fileStream)
req.ContentLength = bodybytes.Length
req.ContentType = mimetype
requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
resp = req.GetResponse()
response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Return fileId
Catch ex As Exception
Return Nothing
End Try
End Function
Shared Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
Dim streamLength As Integer = Convert.ToInt32(stream.Length)
Dim fileData As Byte() = New Byte(streamLength) {}
stream.Position = 0
' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Close()
ReDim Preserve fileData(fileData.Length - 2)
Return fileData
End Function
Public Shared Function MD5stream(ByVal File_stream As IO.Stream, Optional ByVal Seperator As String = Nothing) As String
Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim Hash() As Byte = MD5.ComputeHash(File_stream)
Return Replace(BitConverter.ToString(Hash), "-", Seperator)
End Using
End Function
Had anyone else the same problem?
I have an application writtine in vb.net 2012. I am creating reports using ReportViewer - I want the ability to click a button to send report as pdf to mail
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.salesTableAdapter.Fill(Me.ordersDataSet.sales)
Me.ReportViewer1.RefreshReport()
Me.salesTableAdapter.Fill(Me.ordersDataSet.sales)
Me.ordersDataSet.sales.DefaultView.RowFilter = String.Format("ser={0}", Form1.SalesDataGridView.Item(0, Form1.SalesDataGridView.CurrentRow.Index).Value)
salesBindingSource.DataSource = Me.ordersDataSet.sales.DefaultView
Me.ReportViewer1.RefreshReport()
End Sub
You can Try this
const string HTML_TAG_PATTERN = "<.*?>";
static string StripHTML(string inputString)
{
return Regex.Replace(inputString, HTML_TAG_PATTERN, string.Empty);
}
public static void sendMessage()
{
var username = "john.doe#gmail.com";
var password = "password";
MailAddress MailFrom = new MailAddress("john.doe#gmail.com");
MailAddress MailTo = new MailAddress("john.doe#gmail.com");
var subject = "TEST SUBJECT";
var attachmentPath = "test.pdf";
var mailBody = "<b>test</b>";
NetworkCredential cred = new NetworkCredential(username, password);
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Port = 587;
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
AlternateView avAlternateView = null;
Encoding myEncoding = Encoding.GetEncoding("UTF-8");
avAlternateView = AlternateView.CreateAlternateViewFromString(StripHTML(mailBody), myEncoding, "text/plain");
mail.AlternateViews.Add(avAlternateView);
avAlternateView = AlternateView.CreateAlternateViewFromString(mailBody, myEncoding, "text/html");
mail.AlternateViews.Add(avAlternateView);
mail.Sender = MailFrom;
mail.From = MailFrom;
mail.ReplyTo = MailFrom;
mail.To.Add(MailTo);
mail.Subject = subject;
mail.SubjectEncoding = Encoding.GetEncoding("UTF-8");
mail.BodyEncoding = Encoding.GetEncoding("UTF-8");
Attachment attachment = new Attachment(attachmentPath);
mail.Attachments.Add(attachment);
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}
}
Please also refer: Reportviewer send email via gmail
http://www.codeproject.com/Articles/32109/Send-Mail-and-Print-Report-in-Report-Viewer-Contro
http://forums.asp.net/t/1622010.aspx
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
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