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
Related
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);
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);
This is my code, i get only ??? chars in message body,
i tried to use property "mm.BodyEncoding = Encoding.UTF8", i also tried to add a header of "utf-8", never works for me
Dim smtp = New SmtpClient()
smtp.EnableSsl = UseSsl
smtp.Host = Host
smtp.Port = Port
smtp.Credentials = Credentials
Dim mm = New MailMessage
mm.From = New MailAddress(Credentials.UserName, ScreenName)
mm.Subject = Subject
mm.Body = "אבג"
mm.IsBodyHtml = True
mm.To.AddRange(addresses)
smtp.Send(mm)
I am trying to make a simple e-mail sending program but it has confused me when it said object reference not set to an instance of an object
Try
Dim mail As MailMessage
Dim client As SmtpClient
Dim SmtpServer As New SmtpClient()
Dim fromAddress As String
Dim toAddress1 As String
Dim toAddress2 As String
Dim toAddress3 As String
Dim subject As String
Dim message As String
SmtpServer.Credentials = New Net.NetworkCredential("*********#gmail.com", "**********")
client.UseDefaultCredentials = False
fromAddress = FromEmail.Text
If ToEmail1.Visible = True Then
toAddress1 = ToEmail1.Text
ElseIf ToEmail1.Visible = True And ToEmail2.Visible = True Then
toAddress1 = ToEmail1.Text
toAddress2 = ToEmail2.Text
ElseIf ToEmail1.Visible = True And ToEmail2.Visible = True And ToEmail3.Visible = True Then
toAddress1 = ToEmail1.Text
toAddress2 = ToEmail2.Text
toAddress3 = ToEmail3.Text
End If
subject = "Subject"
Message = "Message"
mail = New MailMessage(fromAddress, toAddress1, subject, Message)
client = New SmtpClient("Smtp.live.com")
client.Port = 587
Dim SMTPUserInfo As New System.Net.NetworkCredential("user#hotmail.com", "password")
client.Credentials = SMTPUserInfo
client.Send(mail)
MsgBox("sent")
Catch ex As Exception
MsgBox(ex.Message.ToString())
End Try
you're declaring two smtpclients
Dim client As SmtpClient
Dim SmtpServer As New SmtpClient()
you instantiated SmtpServer, but not client. Then you do
client.UseDefaultCredentials = False
I guess this is where the exception is raised.
the code looks like having some lines to send some mail through SmtpServer from a google account and other lines to send some mail through client from a hotmail account. Besides, SmtpServer is using some server defined in config.sys.
I have my crystal reports file accessing data from msaccess database.
now while loading report i need to pass the logon info of the msaccess database along with the database name from vb.net.
I tried using
Dim ConnInfo As ConnectionInfo = New ConnectionInfo()
CRpt.ReportOptions.EnableSaveDataWithReport = False
ConnInfo.IntegratedSecurity = False
ConnInfo.ServerName = ""
ConnInfo.UserID = ""
ConnInfo.Password = ""
ConnInfo.DatabaseName = OLEDBLayer.GetDBLocation()
ConnInfo.Type = ConnectionInfoType.DBFile
'CCINFo.ServerName =
For Each CTable As Table In CRpt.Database.Tables
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ConnectionInfo = ConnInfo
'CTable.Location = OLEDBLayer.GetDBLocation
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
But not working. What am i missing?
You can use the following code to apply certain connection details for a report at run time.
Sorry, code in c#.
Please use that method just after loading report rpt file, and before printing/exporting/viewing it.
public static void CrystalReportLogOn(ReportDocument reportParameters,
string serverName,
string databaseName,
string userName,
string password)
{
TableLogOnInfo logOnInfo;
ReportDocument subRd;
Sections sects;
ReportObjects ros;
SubreportObject sro;
if (reportParameters == null)
{
throw new ArgumentNullException("reportParameters");
}
try
{
foreach (CrystalDecisions.CrystalReports.Engine.Table t in reportParameters.Database.Tables)
{
logOnInfo = t.LogOnInfo;
logOnInfo.ReportName = reportParameters.Name;
logOnInfo.ConnectionInfo.ServerName = serverName;
logOnInfo.ConnectionInfo.DatabaseName = databaseName;
logOnInfo.ConnectionInfo.UserID = userName;
logOnInfo.ConnectionInfo.Password = password;
logOnInfo.TableName = t.Name;
t.ApplyLogOnInfo(logOnInfo);
t.Location = t.Name;
}
}
catch
{
throw;
}
sects = reportParameters.ReportDefinition.Sections;
foreach (Section sect in sects)
{
ros = sect.ReportObjects;
foreach (ReportObject ro in ros)
{
if (ro.Kind == ReportObjectKind.SubreportObject)
{
sro = (SubreportObject)ro;
subRd = sro.OpenSubreport(sro.SubreportName);
try
{
foreach (CrystalDecisions.CrystalReports.Engine.Table t in subRd.Database.Tables)
{
logOnInfo = t.LogOnInfo;
logOnInfo.ReportName = reportParameters.Name;
logOnInfo.ConnectionInfo.ServerName = serverName;
logOnInfo.ConnectionInfo.DatabaseName = databaseName;
logOnInfo.ConnectionInfo.UserID = userName;
logOnInfo.ConnectionInfo.Password = password;
logOnInfo.TableName = t.Name;
t.ApplyLogOnInfo(logOnInfo);
}
}
catch
{
throw;
}
}
}
}
}
I searched alot and finally after testing my self by creating new report using static data i got the solution for dynamic one.
My test Procedure:
1.) Created new Crystal Report file:
2.) Created new Database Connection to the .accdb access 2007 file
3.) Created new Form
4.) Added Crystal Report Viewer control on the form
5.) Assigned the report document to the previously created report.
6.) set break point on load of the form
7.) Read all the settings
8.) Copied the settings of the report document, document tables logon info.
9.) Pasted the settings read to my project.
10.) Worked fine... :)
My Code :
//here crpt is a sample report document
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
ConnInfo.Type = ConnectionInfoType.CRQE
ConnInfo.ServerName = DBLayer.GetAbsoluteDBPath()
ConnInfo.DatabaseName = ""
ConnInfo.UserID = "Admin"
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
For Each CTable As Table In CRpt.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CRpt.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
CrystalReportViewer1.ReportSource = CRpt
CrystalReportViewer1.RefreshReport()
I got the point that setting the database path to the servername would resolve that
Try this out:
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
Dim CRpt As New ReportDocument
String filename = "rptSales.rpt"
ConnInfo.Type = ConnectionInfoType.CRQE
ConnInfo.ServerName = AppSettings("server")
ConnInfo.DatabaseName = AppSettings("dbNm")
ConnInfo.UserID = AppSettings("username")
ConnInfo.Password = AppSettings("pas")
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
CRpt.Load(AppSettings("reppath") & filename)
For Each CTable As Table In CRpt.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CRpt.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplCTableLogInfo)
Next