Attachments don't work when sending email after deploying to azure - c#

I have a web application that sends emails from one gmail account to another to notify me that an event has occurred on my website. Working locally it works as intended, I am able to send emails with a body, subject and attachments as expected. However, When I deploy my application to azure the attachments are removed, there isn't anything suggesting that the email was modified on either email.
Here is the code that is used to send the email:
using (MailMessage mail = new MailMessage())
{
try
{
if (userImageStream.Length > 0)
{
mail.Attachments.Add(new Attachment(userImageStream, "Customer.jpg", "image/jpeg"));
}
if (exImageStream.Length > 0)
{
mail.Attachments.Add(new Attachment(exImageStream, "Example.jpg", "image/jpeg"));
}
}
catch (Exception ex) { }
mail.From = new MailAddress(maileraddress);
mail.To.Add(mailTarget);
mail.Subject = "subject";
mail.Body = mailBody;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.Credentials = new System.Net.NetworkCredential(maileraddress, password);
smtp.EnableSsl = true;
await smtp.SendMailAsync(mail);
}
}
I have tried quite a few things programmatically. I can say that for sure the files are uploaded either to a stream or file (depending on configuration). I tried making a outlook account with the gmail email and using smtp.live.com which also didn't work. I think this has something to do with azure (which i have just started using a day or two ago) and I have no idea where to go or what to do. I have seen something about this problem occurring when people are downloading from blobs (I don't know what that is, and i really don't want to yet if possible) but I couldn't figure out how to leverage that answer to solve my problem. I really am stuck here and any help is greatly appreciated. Please keep in mind that I am a novice programmer and my knowledge of azure is basically just enough to get a website up.
After some more testing it appears the files are still null after upload. I'm not saving to file system only to a variable so I'm still confused.
Update: managed to ssh into server, it appears the files aren't being saved. I'm still looking into it any insight will be appreciated.
Can anyone answer if it is even possible to deal with a file that is temporarily uploaded with out being required to use blob storage?
Apparently I dont need to use blob storage but I cant get it to save anyways even with webrootpath. I decided to go back to using streams again and it sends a file but it cant be opened, I'm guessing it might be fixed but I'm not sure. I'll update if I find solution.
Finally- after going back to using streams it works. I'm frustrated that I missed it before chasing my tail but here I am and its finished.

Related

Automate Sending an email through Microsoft Outlook

I am new to C# and I am attempting to automate sending an email from Outlook through the following code and it works fine in the development environment. I would like it to use the default user as the sender even if outlook is not open.
private void EmailMessage(string recipient, string subject, string body)
{
Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem email = (Outlook.MailItem)application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
try
{
email.Subject = subject;
email.Body = body;
email.To = recipient;
((Outlook._MailItem)email).Send();
_emailConfirmation = true;
}
catch (System.Runtime.InteropServices.COMException ex)
{
Logging.LogError("Trip Email Failed", ExceptionHelper.GetInnerMostException(ex));
_emailConfirmation = false;
}
finally
{
//release the objects used to send email after message has been sent\\
if (email != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(email);
if (application != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
}
}
All users are assigned an account and have Outlook installed with a valid anti-virus. My concern is when it goes live, it will fail on the creation of a new instance of outlook or something else I am just not seeing. Do you think this will work with what I intend to accomplish when it goes live?
There is no error in the code, however I am seeing a lot of posts from people saying that you should not create an instance of outlook.application directly.
https://msdn.microsoft.com/en-us/library/office/bb622502.aspx
I think I may just be paranoid because I've never used a PIA before
There can be two main reasons why your code fails:
You get a security issue. See Outlook "Object Model Guard" Security Issues for Developers for more information about the issue and possible ways to bridge the gap and suppress or avoid such issues. Be aware, in some cases the dialog window will not be shown to a user, you just got an exception in the code.
The Click2Run edition of Office 2010 doesn't support automation. See Office 2010 Click-to-Run compatibility with add-ins for more information. Also you may find the How to: Verify Whether Outlook Is a Click-to-Run Application on a Computer article.
Try to use the Recipients property instead of the To field. And then use the Resolve or ResolveAll methods. See How To: Fill TO,CC and BCC fields in Outlook programmatically for more information.
Also I'd recommend adding any logging mechanisms to the code. So, you can analyze the log files and understand what is going on under the hood. For example, consider using the log4net library.

Error while sending attachment with email after publishing the site

I want to send a text file as an attachment with email. When I run my code on local development server it runs properly and file gets attached. But when I publish the site on server, it doesn't pick the attachment and the mail is also not sent. Its not an issue of sending mails, because I have checked it by sending mail without attachment and the mail is sent. The problem is only while attaching file. I have written the path for text file attachment as
string filepath=#"E:\Pwavel\Attachfile\" + filename;
Attachment MyAttachment = new Attachment(filepath);
objmsg.Attachments.Add(MyAttachment);
I have also created "Pwavel" and "Attachfile" folders in E: drive of server.
Is there a problem in path? Or any permission issue? I am not able to understand what the problem is. Please Help me...
If your tests are working on your development machine then this does sound very much like a permission issue.
If you have the authority I'd suggest going to your Attachfile folder and adding Read permission for "Everyone", just to test. If this works you can target specific user / permissions depending on what version of IIS you are using by looking at this:
http://www.iis.net/learn/get-started/planning-for-security/understanding-built-in-user-and-group-accounts-in-iis
Hope this helps.

Saving an auto-generated email? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to save MailMessage object to disk as *.eml or *.msg file
I am working on a C# program that emails people when certain conditions are met. I want to be able to save a copy of the email for record keeping and can't figure it out. I find it surprising there is just not a built it function like message.Save().
I have included a very basic email sample below:
MailMessage message = new MailMessage("from_email", "to_email");
message.Subject = "Email Alert";
message.Body = "This is a test email.";
SmtpClient Smtp = new SmtpClient("smtp server");
Smtp.Send(message);
I would like to save a copy of the email for a record. I didn't really consider all the choices of ways to store the message, sorry for that. I would like to have copy in case the recipient didn't receive the email I could forward them a copy from archive. I think a .msg would work well.
Another addition, I would like to be able to save the email and then send a batch at the end of the day. In case I receive updates that needed to be added I could have to program add new entries to the email so that recipient wouldn't be overloaded with multiple emails. However, there would be some cases where their would be escalation level when met an email would automatically be sent regardless of the time of day.
Why not BCC the email to an admin account?
Well, you weren't too specific about what you were looking for, so here are a few options:
BCC yourself. This will (privately) send yourself a copy of the email.
Implement a save yourself if you want to save to file. It's not that hard. Really all you want to do is save a few bits of text. We could implement it like this:
private void SaveEmailToDisk(MailMessage message, string saveTo)
{
var builder = new StringBuilder();
builder.AppendFormat("To: {0}\n", String.Join("; ", message.To.Select(m => m.Address).ToArray()));
builder.AppendFormat("From: {0}\n",message.From.Address);
builder.AppendFormat("Subject: {0}", message.Subject);
builder.AppendFormat("Body: {0}", message.Body);
File.WriteAllText(saveTo, builder.ToString());
}
Of course you can tweak it to whatever needs you have.
A couple of different ways to "back up" your email messages so they could be resent if necessary:
ProcMail. Depending on the MTA you're using, it would be easy enough to write a ProcMail recipe to archive messages as your MTA sends them. If you're using Exchange, the same can be done on the server side of things.
XML Serialization. After you create each instance of the MailMessage class, serialize it and store it, either in the file system, or in a database. Should be easy enough to rehydrate instance when needed.
Pickup Directory. The SmtpClient class can be configured to "send" messages to a "Pickup Directory." This is normally used in a configuration where the MTA (message transport agent) is configured to watch a particular directory. Sending mail then consists of dropping a file containing an RFC 2822-compliant message into the directory, where it will shortly get collected by the MTA and sent on its way. If no MTA is configured to watch the pickup directory, the mail message will just get dropped there and sit.
This is a useful way of testing the app that does the mailing without involving a real MTA. People tend to get grumpy when they get slammed with junk messages.
It's also a useful technique for archiving: Configure 2 SmtpClient instances in your program: one configured to talk to your MTA and the other configured to drop the message in a pickup directory. Post each MailMessage you create to both instances and you'll have your archive.
Any one of these techniques should work for you. If you actually need to re-send the email, XML serialization might be the best option for you, as rehydrating an object instance is pretty trivial to do via XML serialization.
The important question to ask here is: Save it to where?
That's why there is not a built-in Save() method. Emails are not typically something that is easily just saved to a file-system (that's not to say they cannot be). But there is a lot of information that is not simply stored, like the To/From address, the Subject line, different parts (ie. MIME alternate parts, attachments).
Use
MailAddress bcc = new MailAddress("youremail#domain.com");
message.Bcc.Add(bcc);
You'll get a copy of the message.
Why not write the data to a database table before sending the email? Then, you have a log of what email was sent.

Easiest way to read hotmail emails

I am looking for a library or a simple way to open a hotmail inbox and read new and old emails. A sample code would be much appreciated.
Thanks SOF.
I had the same problem and the gentleman from asp.net show me this link to go download openpop: http://hpop.sourceforge.net/
The link has a test project. But all I needed was:
Pop3Client pop3Client = new Pop3Client();
pop3Client.Connect("pop3.live.com", 995, true);
pop3Client.Authenticate("user", "password");
Message message = pop3Client.GetMessage(10);
string messageText = message.ToMailMessage().Body;
if you want to go with imap protocol ... this may help : using c# .net librarires to check for IMAP messages from gmail servers

Send eml files saved on disk

I am creating eml's and saving them to a directory using procedure mentioned over here.
I want to know how to send these eml files?
I tried using SMTPClient class's object but it takes MailMessage object as its parameter and I couldn't find and way to create an object of type MailMessage using these saved eml files.
Loading an EML file correctly is not as easy as it looks. You can write an implementation working in 95% cases within few days. Remaining 5% would take at least several months ;-). I know, becase I involved in developing one.
Consider following dificulities:
unicode emails
right-to-left languages
correcting malformed EML files caused by well known errors in popular mail clients and servers
dealing with S/MIME (encrypted and signed email messages)
dealing correctly with several methods of encoding attachments
dealing with inline images and stylesheets embedded into HTML emails
making sure that it parses correctly a MIME torture message from Mike Crispin (coauthor of Mime and IMAP RFCs)
making sure that malformed message will not result in buffer overun or other application crash
handling hierarchical messages (message with attached messages)
making sure that it handles correctly very big emails
Maturing of such parser takes years and continuous feedback for it's users. Right now is no such parser included in the .NET Framework. Until it changes I would sugest getting a thrid party MIME parser from an established vendor.
Following code uses our Rebex Secure Mail component, but I'm sure that similar task could be replicated easily with components from other vendors as well.
The code is based on Mail Message tutorial.
// create an instance of MailMessage
MailMessage message = new MailMessage();
// load the message from a local disk file
message.Load("c:\\message.eml");
// send message
Smtp.Send(message, "smtp.example.org");
Use EMLReader to retrieve data from .eml file. It contains all the data you need to create a MailMessage object like From, To, Subject, Body & a whole lot more.
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite);
EMLReader reader = new EMLReader(fs);
fs.Close();
MailMessage message = new System.Net.Mail.MailMessage(reader.From, reader.To, reader.Subject, reader.Body);
If you're a Microsoft shop and have an Exchange server anyway, then there's another solution which is much, much easier than everything else suggested here:
Each Exchange server has a pickup directory configured out of the box.
By default, it's %ExchangeInstallPath%TransportRoles\Pickup.
You just copy the .eml files to that directory, and Exchange automatically will send the mails.
Read this TechNet article for more information:
Pickup directory and Replay directory
As others demonstrated, EML is just not a good way to serialize a mail message. You might be better off by saving your mails in another format. While there are several serialization engines in the .Net framework to serialize any object, you might also consider just saving the components of your mails, like addresses, body, files to be attached in base64, in an Xml file of your own design.
Below is an example to get you started:
<?xml version="1.0" encoding="utf-8"?>
<mail>
<to display="Thomas Edison" address="tedison#domain.com" />
<body>
Hi Thomas,
How are you doing?
Bye
</body>
<attachment name="MaryLamb.wav">
cmF0aWUgYWFuIGluIFBERi1mb3JtYWF0LiBEZSBmYWN0dXVyIGlzIGVlbiBvZmZpY2ll
ZWwgZ2VzaWduZWVyZA0KZG9jdW1lbnQgdmFuIEV1cm9maW5zIE9tZWdhbSBCVi4gRGUg
c2lnbmF0dXJlIGt1bnQgdSB2ZXJpZmnDq3Jlbi4NCg0KVm9vciBoZXQgdmVyaWZpw6ty
...
</attachment>
</mail>
Added advantage would be that, unlike with creating EML, you do not need the smtpClient to build the concept mail files.
Xml is extremely easy to create and parse in C#.
You did not tell the rationale of saving EML's. If long term archival would be a goal, xml might have an advantage.
Do What i did ... give up.
Building the MailMessage object seems to be the focus i have a similar questions outstanding on here too ...
How do i send an email when i already have it as a string?
From what i've seen the simplest way to do this is to use a raw socket to dump the entire .eml file contents up to the mail server as is and let the mail server figure out the hard stuff like from, to subject, ect by parsing the email using it's engine.
The only problem ... RFC 821 ... such a pain, i'm trying to figure out a clean way to do this and read mail already in the mailbox quickly too.
EDIT:
I found a clean solution and covered it in my thread :)
How do i send an email when i already have it as a string?
You can do this with Windows Server’s built-in SMTP server, the same way as in the previous answer using Exchange.
Drop the .eml file to C:\inetpub\mailroot\Pickup and the raw message will be sent (local or remote).
You can forward messages by simply inserting a line in the top:
To: email#address.com
You can manipulate the mail header further if you require.
For the records:
In Nuget Packager Console write:
Install-Package LumiSoft.Net.dll
Then in your Code:
using (FileStream fs = new FileStream( cacheFileName, FileMode.Open, FileAccess.Read ))
using (LumiSoft.Net.SMTP.Client.SMTP_Client client =
new LumiSoft.Net.SMTP.Client.SMTP_Client())
{
client.SendMessage( fs );
}

Categories

Resources