Mail pdf Attachment using Rotativa - asp.net-mvc

Sending the email and the attachment actaly works. my issue is i get this error when trying to send the "generated pdf"
An exception of type 'System.Exception' occurred in Rotativa.dll but was not handled in user code
Additional information: Error: Failed loading page http://localhost:49224/Offer/OfferPdf/4 (sometimes it will work just to ignore this error with --load-error-handling ignore)
The mail test in the controller:
public ActionResult MailTest()
{
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(CoEmail));
msg.From = new MailAddress(MailFrom, UserName);
msg.Subject = "Offer";
msg.Body = "This is a Test";
MemoryStream stream = new MemoryStream(OffersPdfMail (4, "Offer"));
Attachment att1 = new Attachment(stream, "Offer.pdf", "application/pdf");
msg.Attachments.Add(att1);
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.SubjectEncoding = System.Text.Encoding.Default;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(User, Pass);
client.Port = 587; //
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
return RedirectToAction("index");
}
catch (Exception ex)
{
return HttpNotFound();
}
}
The Byte[]:
public Byte[] OfferPdfMail(int? id, string filename)
{
var mailpdft = new ActionAsPdf("OfferPdf/4")
{
FileName = "Offer",
PageSize = Rotativa.Options.Size.A4,
PageWidth = 210,
PageHeight = 297
};
Byte[] PdfData = mailpdft.BuildPdf(ControllerContext);
return PdfData;
and last the ViewasPdf:
public ActionResult OfferPdf (int? id, string filename)
{
string footer = "test" ;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var pdf = new ViewAsPdf("TilbudsPdf") {
FileName = filename,
PageSize = Rotativa.Options.Size.A4,
PageOrientation = Rotativa.Options.Orientation.Portrait,
PageMargins = new Rotativa.Options.Margins(12, 12, 12, 12),// it’s in millimeters
PageWidth = 210,
PageHeight = 297,
CustomSwitches = footer };
return pdf;
}
Editted the names to english. may have missed some.
Thanks for your patience, and sorry for the bad english.
Best regards Eric

I found an solution, it was because i was stupid trying to making an pdf of a pdf. so i made a new ActionResult method like this:
public ActionResult tilbudspdfMailView(int? id, string filename)
{
Offer Offer= db.Offer.Find(id);
return View("OfferPdf", Offer);
}

Related

How to change email file's extension?

I am using this class to send an email with a PDF attachment. The class has the following code:
using System.IO;
using System.Net;
using System.Net.Mail;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.Web.WebDocumentViewer;
using DevExpress.XtraReports.Web.WebDocumentViewer.DataContracts;
namespace DocumentOperationServiceSample.Services
{
public class CustomDocumentOperationService : DocumentOperationService {
public override bool CanPerformOperation(DocumentOperationRequest request)
{
return true;
}
public override DocumentOperationResponse PerformOperation(DocumentOperationRequest request, PrintingSystemBase initialPrintingSystem, PrintingSystemBase printingSystemWithEditingFields)
{
using (var stream = new MemoryStream()) {
printingSystemWithEditingFields.ExportToPdf(stream);
stream.Position = 0;
var mailAddress = new MailAddress(request.CustomData);
var recipients = new MailAddressCollection() { mailAddress };
var attachment = new Attachment(stream, System.Net.Mime.MediaTypeNames.Application.Pdf);
return SendEmail(recipients, "Enter_Mail_Subject", "Enter_Message_Body", attachment);
}
}
DocumentOperationResponse SendEmail(MailAddressCollection recipients, string subject, string messageBody, Attachment attachment) {
string SmtpHost = null;
int SmtpPort = -1;
if (string.IsNullOrEmpty(SmtpHost) || SmtpPort == -1) {
return new DocumentOperationResponse { Message = "Please configure the SMTP server settings." };
}
string SmtpUserName = "Enter_Sender_User_Account";
string SmtpUserPassword = "Enter_Sender_Password";
string SmtpFrom = "Enter_Sender_Address";
string SmtpFromDisplayName = "Enter_Sender_Display_Name";
using (var smtpClient = new SmtpClient(SmtpHost, SmtpPort))
{
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
if (!string.IsNullOrEmpty(SmtpUserName))
{
smtpClient.Credentials = new NetworkCredential(SmtpUserName, SmtpUserPassword);
}
using (var message = new MailMessage())
{
message.Subject = subject.Replace("\r", "").Replace("\n", "");
message.IsBodyHtml = true;
message.Body = messageBody;
message.From = new MailAddress(SmtpFrom, SmtpFromDisplayName);
foreach (var item in recipients)
{
message.To.Add(item);
}
try
{
if (attachment != null)
{
message.Attachments.Add(attachment);
}
smtpClient.Send(message);
return new DocumentOperationResponse
{
Succeeded = true,
Message = "Mail was sent successfully"
};
}
catch (SmtpException e)
{
return new DocumentOperationResponse
{
Message = "Sending an email message failed."
};
}
finally
{
message.Attachments.Clear();
}
}
}
}
protected string RemoveNewLineSymbols(string value)
{
return value;
}
}
}
It works fine, but when I receive the email it has attached an document named application/pdf.
I was trying to find out where the document's name comes from. As you can see in the below image, when I add the application type PDF, it appears exactly what I get attached in email.
The problem is that application/pdf cannot be opened with any PDF viewer app. I have to rename the document to application.pdf in order to be able to open it. Is there a way to change application/pdf with application.pdf?
If anyone is looking for the answer:
var attachment = new Attachment(stream, "report.pdf ", System.Net.Mime.MediaTypeNames.Application.Pdf);

MS Graph SendMail with attachment

I have problem to send an email with attachment.
Without attachment it works.
If I use the same function and add an attachment to the message I get the following error message:
Code: ErrorRequiredPropertyMissing Message: Required property is missing. ClientRequestId: 2af....
I am using MS Graph v4.0.30319
What am I doing wrong
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#mail.com"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\me\Desktop\Test.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
//ODataType = "#microsoft.graph.fileAttachment",
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#MailNo2.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
// -- If I comment this out I can send the mail without error but without attachment----
message.Attachments.Add(attachment);
message.HasAttachments = true;
//-----------------------------------------------------------------
var request = graphClient.Me.SendMail(message, true);
// Messages[message.Id].Send();// SendMail(message, null);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
The below code works perfectly fine for me
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\Shiva\Desktop\sample.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
message.HasAttachments = true;
message.Attachments.Add(attachment);
var request = graphClient.Me.SendMail(message, true);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
You need to make sure that you have the PDF file path correctly specified and the fromSender variable will obviously be yours as you are calling me/sendMail. If you want to send mail from other user's mailbox then you need to have client credential flow setup so that it can give you an App-only token which should have required permissions and you need to change the call something like this var request = graphClient.Users["userid/UPN"].SendMail(message, true);.
I have just updated the MS Graph preview version from
4.0.0-preview.1
to
4.0.0-preview.2
Now everything works as expected
I think it was a bug in preview.1

There is no argument given that corresponds to the required formal parameter 'key' of 'IOwinContext.Get<T>(string)'

I am trying to add a profile picture to my project and I am following this article
https://social.technet.microsoft.com/wiki/contents/articles/34445.mvc-asp-net-identity-customizing-for-adding-profile-image.aspx#Step_4_IdentityModels_cs
and in the article there is a part where I have to get the user details to load the user's image. At this step I get the error in the heading, what am I missing?
public FileContentResult UserPhoto()
{
if (User.Identity.IsAuthenticated)
{
String userId = User.Identity.GetUserId();
if (userId == null)
{
string filename =
HttpContext.Server.MapPath(#"~/Uploads/ProfilePictures/blankprofile.png");
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(filename);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(filename, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return File(imageData, "image/png");
}
// to get the user details to load user Image
var bdUsers =
HttpContext.GetOwinContext().Get<ApplicationDbContext>();
var userImage = bdUsers.Users.Where(x => x.Id ==
userId).FirstOrDefault();
return new FileContentResult(userImage.ProfilePicture,
"image/jpeg");
}
else
{
string fileName =HttpContext.Server.MapPath(#"~/Uploads/ProfilePictures/blankprofile.png");
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(fileName);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(fileName, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return File(imageData, "image/png");
}
}
You have to reference the Microsoft.AspNet.Identity.Owin namespace. It has the class that has the Get method you are looking for.

ASP.Net MVC File Upload and Attach to Email

I'm developing an ASP.Net MVC 3 web application. One of my Razor Views allows a user to upload a file (selected from their computer) and then this is attached to an outgoing email.
Below is my code to date, but unfortunately it does not work. By this I mean the email (and of course the attachment) never gets sent. Although, when I step threw/ debug my code locally no errors occur, and none as well on the live server.
Does anyone see what I'm missing? Any advice would be greatly appreciated.
Thanks.
Controller
[HttpPost]
public ActionResult CvUpload(HttpPostedFileBase file)
{
//Get logged in user
User user = _accountService.GetUser(_formsAuthService.GetLoggedInUserID());
if (file != null && file.ContentLength > 0)
{
_emailService.SendUpload(user, file);
return RedirectToAction("CvUpload", new { feedBack = "Success" });
}
return RedirectToAction("CvUpload", new { feedBack = "Failed" });
}
Email Service
public void SendUpload(User user, HttpPostedFileBase file)
{
string messageBody = "";
string subject = "Upload";
string[] toAddress = new string[1];
string ToBCC = "";
if (isProduction.Equals("true"))
{
toAddress[0] = "myemail#test.com";
sendEmail(toAddress, ToBCC, adminFromEmail, adminFromEmail, subject, messageBody, true, emailServer, file);
}
else
{
// DO NOT SEND EMAIL
}
}
private bool sendEmail(string[] toAddresses, string ToBCC, string fromAddress, string replyto, string subject, string body, bool ishtml, string emailHost, HttpPostedFileBase file)
{
bool mailSent = false;
try
{
MailMessage mail = new MailMessage();
foreach (string addresss in toAddresses)
mail.To.Add(addresss);
mail.From = new MailAddress(fromAddress);
mail.ReplyToList.Add(replyto);
mail.Bcc.Add(ToBCC);
mail.Subject = subject;
mail.Body = body;
if(file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
mail.Attachments.Add(new Attachment(file.InputStream, fileName));
}
if (ishtml)
mail.IsBodyHtml = true;
else
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = emailHost;
smtp.Send(mail);
mailSent = true;
}
catch (Exception)
{
mailSent = false;
}
return mailSent;
}
I have a similar service and this is what I have although the attachments are saved so they can be reused later.
var attachment = new Attachment(path);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(path);
disposition.ModificationDate = File.GetLastWriteTime(path);
disposition.ReadDate = File.GetLastAccessTime(path);
disposition.FileName = attachmentName.Name;
disposition.Size = new FileInfo(path).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mailMessage.Attachments.Add(attachment);

MVC system.net.mail

Hi I am having difficulties sending email to registered users.I get exception error in the line:
msg.To.Add(new MailAddress(newsletter.AspNetUser.Email));
Error:
An exception of type 'System.NullReferenceException' occurred in MVCHarmony.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
Following is my code.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "NewsLetterId,Headerline,Description,Photo,NewsletterFile,Id")] Newsletter newsletter, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
StringBuilder sb = new StringBuilder();
msg.From = new MailAddress("abc#hotmail.com");
msg.To.Add(new MailAddress(newsletter.AspNetUser.Email));
msg.Subject = "Newsletter";
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var attachment = new Attachment(file.InputStream, fileName);
msg.Attachments.Add(attachment);
}
msg.IsBodyHtml = false;
sb.Append("" + newsletter.Headerline);
sb.Append(Environment.NewLine);
sb.Append("" + newsletter.Description);
sb.Append(Environment.NewLine);
msg.Body = sb.ToString();
smtp.Host = "smtp.live.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("abc#hotmail.com", "*******");
smtp.Send(msg);
db.Newsletters.Add(newsletter);
db.SaveChanges();
msg.Dispose();

Resources