How to change email file's extension? - asp.net-mvc

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);

Related

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

Emailing recurring invoices using quartz.net in asp.net mvc

I am working on asp.net MVC application that needs to email recurring invoices to customers, i am trying to use quartz.net. I have to email invoice as attachment to every customer on certain date once in the month. I can send email with Quartz without attachments, but when i add attachment it doesn't send, when i click button that is linked with emailing method it does send email to every customers with the invoice attachment. Schedule emails are stored in database and invoices are generated in PDF using Rotativa. Here is my code:
public class Jobclass : IJob
{
public void Execute(IJobExecutionContext context)
{
InvoiceAddlinesController sche = new InvoiceAddlinesController();
sche.Recurring();
}
}
public void Recurring()
{
int originalId = 0;
string companyname = "";
int suc = 0;
string userloggedin = "";
string loggedemail = "";
string password = "";
string Subject = "";
string Message = "";
string bar = "";
string countDown = "";
int seconds = 10;
decimal? totalamount = 0;
var scheduling = from e in db.Invoices
where e.schedule == "Schedule"
select e;
var sched = scheduling.ToList();
foreach (var y in sched)
{
companyname = y.SchedCompanyname;
originalId = y.SchedCustomerId;
loggedemail = y.SchedLoggedemail;
password = y.SchedPassword;
userloggedin = y.SchedRt;
totalamount = y.SchedTotal;
Subject = y.SchedSubject;
Message = y.SchedMassage;
bar = loggedemail.ToString();
bar.Split(';');
using (var message = new MailMessage("myemail#gmail.com", bar))
{
var roata = from e in db.InvoiceAddlines
where e.AddlineID == originalId && e.userId == userloggedin
select e;
var roatainum = roata.ToList();
var model = roatainum;
message.Subject = "Message Subject test";
message.Body = "Message body test at " + DateTime.Now;
var pdf = new ViewAsPdf2("Gem", model, ViewBag.ind = originalId, TempData["user"] = userloggedin);
byte[] pdfByteArray = pdf.GetByte(ControllerContext);
message.IsBodyHtml = true;
MemoryStream file = new MemoryStream(pdfByteArray);
file.Seek(0, SeekOrigin.Begin);
Attachment data = new Attachment(file, "Invoice_Attachment.pdf", "application/pdf");
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.DateTime.Now;
disposition.ModificationDate = System.DateTime.Now;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(data);
using (SmtpClient client = new SmtpClient
{
EnableSsl = true,
Host = "smtp.gmail.com",
Port = 587,
Credentials = new NetworkCredential("myemail#gmail.com", "#P#iop234")
})
{
client.Send(message);
}
}
}
}
I have no idea what i am doing wrong.

How to Inject to EmailMessageService

I'm having problem with injecting my service. I've a ISettingService. I'm testing registration onmy application and using email confirmation.
So, at the EmailMessageService class which is inherit from IIdentityMessageService
I'm using Unity for Ioc. I'd registered ISettingService at unity config like below
.RegisterType<ISettingService, SettingService>()
I need to inject this interface to EmailMessageService class to access settings.
Here is the EmailMessageService class
public class EmailMessagingService : IIdentityMessageService
{
private ISettingService SettingService { get; set; }
public Task SendAsync(IdentityMessage message)
{
var fromEmailAddress = ConfigurationManager
.AppSettings["IdentityFromEmailAddress"];
var text = message.Body;
var html = message.Body;
// Do whatever you want to the message
using (var msg = new MailMessage())
{
msg.From = new MailAddress(fromEmailAddress);
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(
text, null, MediaTypeNames.Text.Plain)
);
msg.AlternateViews.Add(
AlternateView.CreateAlternateViewFromString(
html, null, MediaTypeNames.Text.Html)
);
// var smtpClient = new SmtpClient("smtp.whatever.net", Convert.ToInt32(587));
// var credentials = new System.Net.NetworkCredential(Keys.EmailUser, Keys.EMailKey);
// smtpClient.Credentials = credentials;
using (var smtpClient = new SmtpClient())
{
var setting = SettingService.Query().Select().FirstOrDefault();
if (setting != null)
{
if (!string.IsNullOrEmpty(setting.SmtpHost))
{
smtpClient.Host = setting.SmtpHost;
smtpClient.Port = Convert.ToInt32(setting.SmtpPort);
if (setting.IsSmtpSsl)
{
smtpClient.EnableSsl = true;
}
}
}
smtpClient.Send(msg);
}
}
return Task.FromResult(0);
}
}
EmailMessageService class instantiating at Startup.Auth
var manager =
new ApplicationUserManager(
new ApplicationUserStore(context.Get<DataContext>()));
...
manager.EmailService = new EmailMessagingService();
I cant use Constructor injecting be cause of this direct call. So i used setter injection. But im getting error like "Object reference not set to an instance of an object"
var setting = SettingService.Query().Select().FirstOrDefault();
in EmailMessageService.
O.K What exacly happend i dont know but by changing UnityMvcActivator Start method like below its fixed.
public static void Start()
{
var container = ContainerManager.GetConfiguredContainer();
UnityConfig.RegisterTypes(container);
FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
try
{
//http://stackoverflow.com/questions/699852/how-to-find-all-the-classes-which-implement-a-given-interface
foreach (var assembly in assemblies)
{
var instances = from t in assembly.GetTypes()
where t.GetInterfaces().Contains(typeof(IDependencyRegister))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as IDependencyRegister;
foreach (var instance in instances.OrderBy(x => x.Order))
{
instance.Register(container);
}
}
}
catch (ReflectionTypeLoadException ex)
{
http://stackoverflow.com/questions/1091853/error-message-unable-to-load-one-or-more-of-the-requested-types-retrieve-the-l
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (Exception exSub in ex.LoaderExceptions)
{
sb.AppendLine(exSub.Message);
System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
if (exFileNotFound != null)
{
if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
{
sb.AppendLine("Fusion Log:");
sb.AppendLine(exFileNotFound.FusionLog);
}
}
sb.AppendLine();
}
string errorMessage = sb.ToString();
throw new Exception(errorMessage, ex);
//Display or log the error based on your application.
}
// TODO: Uncomment if you want to use PerRequestLifetimeManager
// Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
}

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);

Stuck up with MessageList in Blackberry

I am try to do MessageList in blackberry using midlet, but whatever I do some expection comes up. Right now am getting NullPointerException. Here is the code
EncodedImage indicatorIcon = EncodedImage.getEncodedImageResource("img/indicator.png");
ApplicationIcon applicationIcon = new ApplicationIcon(indicatorIcon);
ApplicationIndicatorRegistry.getInstance().register(applicationIcon, false, false);
ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();
MessageListStore messageStore = MessageListStore.getInstance();
if(reg.getApplicationFolder(INBOX_FOLDER_ID) == null)
{
ApplicationDescriptor daemonDescr = ApplicationDescriptor.currentApplicationDescriptor();
String APPLICATION_NAME = "TestAPP";
ApplicationDescriptor mainDescr = new ApplicationDescriptor(daemonDescr, APPLICATION_NAME, new String[] {});
ApplicationFolderIntegrationConfig inboxIntegration = new ApplicationFolderIntegrationConfig(true, true, mainDescr);
ApplicationFolderIntegrationConfig deletedIntegration = new ApplicationFolderIntegrationConfig(false);
ApplicationMessageFolder inbox = reg.registerFolder(MyApp.INBOX_FOLDER_ID, "Inbox", messageStore.getInboxMessages(),
inboxIntegration);
ApplicationMessageFolder deleted = reg.registerFolder(MyApp.DELETED_FOLDER_ID, "Deleted Messages", messageStore.getDeletedMessages(), deletedIntegration);
messageStore.setFolders(inbox, deleted);
}
DemoMessage message = new DemoMessage();
String name = "John";
message.setSender(name);
message.setSubject("Hello from " + name);
message.setMessage("Hello Chris. This is " + name + ". How are you? Hope to see you at the conference!");
message.setReceivedTime(System.currentTimeMillis());
messageStore.addInboxMessage(message);
messageStore.getInboxFolder().fireElementAdded(message);
Can someone suggest me a simple MessageList sample for midlet to just show a String in MessageList and custom ApplicationIndicator value. If possible OnClick of message bring back the midlet from background.
use the following code:
static class OpenContextMenu extends ApplicationMenuItem {
public OpenContextMenu( int order ) {
super( order );
}
public Object run( Object context ) {
if( context instanceof NewMessage ) {
try {
NewMessage message = (NewMessage) context;
if( message.isNew() ) {
message.markRead();
ApplicationMessageFolderRegistry reg = ApplicationMessageFolderRegistry.getInstance();
ApplicationMessageFolder folder = reg.getApplicationFolder( Mes
sageList.INBOX_FOLDER_ID );
folder.fireElementUpdated( message, message );
//changeIndicator(-1);
}
Inbox inbox = message.getInbox();
Template template = inbox.getTemplate();
//Launch the mainscreen
UiApplication.getUiApplication().requestForeground();
}
catch (Exception ex) {
Dialog.alert();
}
}
return context;
}
public String toString() {
return "Name of the menu item";
}
}

Resources