How to open default email client with attachment - c#

I'm working on an issue to my project that when I click the button, a default email client should pop out and if there's an attachment, it should be automatically attach to the default email client like this.
I already tried a lot of methods how to do this. First I used MAPI, but the MAPI cannot detect my Default Email Client even though I already set it in Control Panel, It shows this two message box
I already searched the internet about those error but there's no definite or clear answer to me. HERE'S the code I used in MAPI.
I used also the mail:to protocol to call the default email client who's handling to the aforementioned protocol with using this line of codes.
Dim proc As System.Diagnostics.Process = New System.Diagnostics.Process()
Dim filename = Convert.toChar(34) & "C:\USERS\JOSHUA~1.HER\DOWNLO~1\ASDPOR~1.PDF" & Convert.toChar(34)
Debug.Writeline(filename)
Dim asd As String = String.Format("mailto:someone#somewhere.com?subject=hello&body=love my body&Attach={0}", filename)
proc.StartInfo.FileName = asd
proc.Start()
But still, no luck. I read a thread that the mail:to don't handle attachment anymore, but this line of code opened my default email client with body and subject, but there's no attachment. In terms of the filename variable, I already tried every path format, I read that I should use 8.3 path format. But still doesn't work.
The last method I used is extending the System.Net.MailMessage.MailMessage() following THIS answer. This works in terms of opening the default email client and attaching an attachment to a mail, but this is not editable and there's no send button on the default email client because this line of code just generating an .eml file and opening it. I'm thinking of parsing the eml file but still I don't know how to open the default email client progmatically in a new message form. Here's the photo
You guys have any idea how to make this possible? Thanks!

I am afraid that this will not be possible to do using some generic method for any mail client. But you can easily create your own solution using System.Net.Mail.SmtpClient and some simple custom UI.

Related

Attaching auto generated pdf to email in asp.net app

I have a very specific requirement. In my web app, I have to generate a pdf invoice from the database values, and an email body. I can easily send this using SMTP which works perfect.
But, problem is we can't rely on system to always be perfect, and this is an invoice. So, we need to open the default mail client instead of using SMTP. Right now, I have following code
//Code to create the script for email
string emailJS = "";
emailJS += "window.open('mailto:testmail#gmail.com?body=Test Mail" + "&attachment=" + emailAttachment + "');";
//Register the script for post back
ClientScript.RegisterStartupScript(this.GetType(), "mailTo", emailJS, true);
This opens the email perfectly, but no attachment is working. Path is supposed to be /Web/Temp/123.pdf.
If I use the same path as normal url like below, it opens the file in new window properly.
ClientScript.RegisterStartupScript(this.GetType(), "newWindow", "window.open('/Web/Temp/123.pdf');", true);
So, clearly file exists, but it exists on the server. Outlook on the other hand open on client machine. So, I can't use the full determined path like C:\Web\Temp\123.pdf. If I try that, it will try to find the file on client machine, where the folder itself might not exist.
I am trying to figure out what can I do here. If there is another method I should try.
P.S. No, I can't send the email directly. That will cause a hell lot more problem in future for me.
Edit:
I also found one weird problem. If I add a double quote to the file path in attachment, a \ is added automatically. #"&attachment=""" + Server.MapPath(emailAttachment) + #"""');" gives me output as &attachment=\"C:\Web\Temp\123.pdf\".
I am trying to escape that double quote and somehow it adds that slash. I know this is a completely different problem, but thought I should mention here, instead of creating a new question.
Edit:
I tried a fixed path on localhost. So, I am basically testing the app on the same machine where file is getting stored. still, no attachment at all.
string emailJS = "";
emailJS += #"window.open('mailto:jitendragarg#gmail.com?body=Test Mail" + emailAttachment + #"&attachment=";
emailJS += #"""D:\Dev\CSMS\CSMSWeb\Temp\635966781817446275.Pdf""');";
//emailJS += Server.MapPath(emailAttachment) + #"');";
//Register the script for post back
ClientScript.RegisterStartupScript(this.GetType(), "mailTo", emailJS, true);
Updated the path to make sure it is proper. Now, it just throws error saying command line argument not valid.
Edit:
Is there any other method I can try? I have the file path on the server side. Maybe I can download the file automatically to some default folder on client machine and open from there? Is that possible?
Edit: I tried one more option.
emailJS += #"mailto:testmail#gmail.com?body=Test Mail" + #"&attachment=";
emailJS += #"\\localhost\CSMSWeb\Temp\635966781817446275.Pdf";
//emailJS += Server.MapPath(emailAttachment) + #"');";
Process.Start(emailJS);
The Process.Start line works but it does nothing at all. There is no process that starts, no error either.
Edit:
yay. I finally got the user to approve using a separate form to display the subject and body, instead of opening the default mail client. although, I would still prefer to solve this problem as is.
So, the problem here is the fact that mailto only supports direct file path for attachment. That is, path has to be local to use machine, or intranet path within the network.
In other words, path like http://yourapp/Web/Temp/123.pdf won't work, and /Web/Temp/123.pdf being essentially the same won't work either. These are not paths, but links to files that has to be downloaded and stored locally before they can be used as attachments - mailto protocol has no support for that.
However, since your application is intranet, what you could do is make sure intended users have access to some network shared folder on your server, and then provide them with network path to the file, that is \\theserver\files\123.pdf

C# Mail pdf attachment utf-8

In my application, i send mails to managers from program automatically. Normally it works good, but when i use program on another computer, it sends mail automatically but file type is not PDF. File type is File and name of pdf is =utf-8BQU5HT1JBIEhBTEkgQS7Fni4gR8OcTkzD. I also checked source codes. But I couldn't understand what is wrong with that. Any idea what to do?
Try to fill the ContentDisposition, example is here:
Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird
Maybe, in the code you can change the MediaTypeNames.Application.Octet to MediaTypeNames.Application.Pdf
I hope, this helps!

How to include the user signature in the email body when sending a customized email through Thunderbird, using C# 3.5?

We need to send email from our desktop application using C# 3.5. The requirement is to send the new email using the Thunderbird, not directly from our application. So we are setting certain properties for the new email like emialfrom, emailto, subject, body & attachments through code, we save it as an .eml file & then we open that .eml file in thunderbird using code:
The logic we are following is:
MyEmailClass eml = new MyEmailClass();
eml.Subject = "subject";
eml.SetHtmlBody(" email body");
eml.From = "from";
email.AddTo = "toemail#domain.com";
email.AttachmentPath = "attachmentpath";
email.SaveEml("myEmail.eml");
So now we have the the .eml file & we need to open it in the Thunderbird, we are using System.Diagnostics.Process.Start to open the eml file in Thunderbird:
System.Diagnostics.Process.Start(thunderbird exe path,myEmail.eml path);
The above works fine, however we have just one issue, the sender signature is not shown when the email opens in the Thunderbird.
Facts:
1- The user has valid signature associated with his account.
2- We are using Thunderbird 8.0
3- We are using C# 3.5
4- Thunderbird is the default email client on users systems.
Signatures are added by the email client when it creates the email body. Since you are creating the email body through code, you would have to programmatically insert the signature. Just to be clear, you are not necessarily launching thunderbird on the user's machine, you are launching whatever process is associated with the .eml file extension. If you want to include the singature from Thunderbird, you could look to see if any of their APIs help, but they look like they haven't been updated in years. You could also give your users the option of setting up their signature within your application.

Generate an e-mail to be downloaded by client and sent from their outlook account

One of the requirements for the application that I'm working on is to enable users to submit a debugging report to our helpdesk for fatal errors (much like windows error reporting).
I've been told that e-mails must come from a client's mail account to prevent the helpdesk getting spammed and loads of duplicate calls raised.
In order to achieve this, I'm trying to compose a mail message on the server, complete with a nice message in the body for the helpdesk and the error report as an attachment, then add it to the Response so that the user can download, open and send it.
I've tried, without success, to make use of the Outlook Interoperability Component which is a moot point because I've discovered in the last 6 hours of googling that creating more than a few Application instances is very resource intensive.
If you want the user to send an email client side, I don't see how System.Net.Mail will help you.
You have two options:
mailto:support#domain.com?subject=Error&body=Error message here...
get user to download email in some format, open it in their client and send it
Option 1 will probably break down with complex bodies. With Option 2, you need to find a format that is supported by all mail clients (that your users use).
With option 1, you could store the email details locally on your server against some Error ID and just send the email with an Error ID in the subject:
mailto:support#domain.com?subject=Error 987771 encountered
In one of our applications the user hits the generate button and it creates and opens the email in outlook. All they have to do is hit the send button. The functions is below.
public static void generateEmail(string emailTo, string ccTo, string subject, string body, bool bcc)
{
Outlook.Application objOutlook = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)(objOutlook.CreateItem(OlItemType.olMailItem));
/* Sets the recipient e-mails to be either sent by 'To:' or 'BCC:'
* depending on the boolean called 'bcc' passed. */
if (!(bcc))
{
mailItem.To = emailTo;
}
else
{
mailItem.BCC = emailTo;
}
mailItem.CC = ccTo;
mailItem.Subject = subject;
mailItem.Body = body;
mailItem.BodyFormat = OlBodyFormat.olFormatPlain;
mailItem.Display(mailItem);
}
As you can see it is outputting the email in plaintext at the moment because it was required to be blackberry friendly. You can easily change the format to HTML or richtext if you want some formatting options. For HTML use mailItem.HTMLBody
Hope this helps.
EDIT:
I should note that this is used in a C# Application and that it is referencing Microsoft.Office.Core and using Outlook in the Email class the function is located in.
The simple answer is that what you are trying to achieve isn't realistically achievable across all platforms and mail clients. When asked to do the improbable it is wise to come up with an alternative and suggest that.
Assuming that your fault report is only accessible from an error page then you've already got a barrier to spam - unless the spammers can force an exception.
I've always handled this by logging the fault and text into the database and integrating that with a ticketing system. Maybe also have a mailto: as Bruce suggest with subject=ID&body=text to allow the user to send something by email.
I don't think an .eml format file will help either - because they'll need to forward it, and most users would probably get confused.
A .eml is effectively plain text of the message including headers as per RFC-5322.

Launching email application (MAPI) from C# (with attachment)

In the past I have used MAPISendMail to launch Outlook (or whatever the desired MAPI email application was) from a C++ application with a file attachment. (Similar to say Microsoft Word's Send Email functionality).
I need to do the equivalent from a C# application and to have it work when running on XP, Vista, Server 2008 (and Windows 7 I suppose).
MAPISendMail is a no go under Vista/2008 as it always returns MAPI_ E_FAILURE when Outlook is running and MAPI is not supported in managed code.
Even after checking this fix:
http://support.microsoft.com/kb/939718
I can't get it to reliably work.
I know that Microsoft Word & Adobe Reader 9 can both launch Outlook with an attachment under Vista.
A C# compatible solution would be preferred but I'd be happy with anything that works (doesn't have to use MAPI). I can't seem to find what the current "solution" is. None of the existing answers on Stack Overflow seem to cover this either.
Edit:
I am aware MAPI and C# do not work together, so I will take a C/C++ solution that works in Vista and Server 2008 when NOT running as administrator. See Adobe Reader 9 & Microsoft Word as examples that work.
At work we have successfully done this using VSTO.
Here is a snippet of some lines we have running on VISTA with Outlook 2007: (the code is in VB.net).
Note that the usage is security locked when doing certain things to the outlook object. (to address, body and other properties marked as security risks). We use a 3rd party component (Redemption) to go around this security. If you dont use a security manager of some sort, outlook will give a little popup that something outside is trying to access it and you can give it access in a period of time.
The import of the Outlook interface.
Imports Outlook = Microsoft.Office.Interop.Outlook
This example is to give you some direction, not a full working example.
dim MailItem As Microsoft.Office.Interop.Outlook.MailItem
' Lets initialize outlook object '
MailItem = OutlookSession.Application.CreateItem(Outlook.OlItemType.olMailItem)
MailItem.To = mailto
MailItem.Subject = communication.Subject
MailItem.BodyFormat = Outlook.OlBodyFormat.olFormatHTML
MailItem.HTMLBody = htmlBody
MailItem.Attachments.Add(filename, Outlook.OlAttachmentType.olByValue)
' If True is supplied to Display it will act as modal and is executed sequential. '
SafeMail.Display(True)
The OutlookSession in the above example is coming from this Property:
Public ReadOnly Property OutlookSession() As Outlook.NameSpace
Get
If Not OutlookApplication Is Nothing Then
Return OutlookApplication.GetNamespace ("MAPI")
Else
Return Nothing
End If
End Get
End Property
As you can see it is using MAPI inside for this.
Good luck with it.
You don't really need redemption for VB as suggested above as long as you are simply setting properties in an e-mail and not reading them. Here is a simple VB function to show / send an e-mail via outlook with an attachment. (This code references the Microsoft Outlook 12.0 Object Library e.g. "C:\Program Files\Microsoft Office\Office12\MSOUTL.OLB").
Sub DoMail()
Set objOL = CreateObject("Outlook.Application")
Set objNewMail = objOL.CreateItem(olMailItem)
Dim filename As String
filename = "C:\\temp\\example.txt"
With objNewMail
.To = "cjoy#spam_me_not.com"
.Subject = "test"
.Body = "Test Body"
.Attachments.Add filename, Outlook.OlAttachmentType.olByValue
End With
objNewMail.Display
'objNewMail.Send
End Sub
Bit lowtech method, but using the mailto handler you can do this
System.Diagnostics.Process.Start("mailto:something#somewhere.com?subject=hello&attachment=c:\\chicken.xls");
Note: As pointed out this may not work on all clients as it is not part of the mailto URL spec. Most importantly (in my world at least) is Outlook 2007 does not support it, while older versions did.
I'm not sure if you need the email to open in outlook or if you just want to send an email with an attachment from c#. I know you wrote open in outlook but you may be assuming this is the only way to do it. If you just want to send an email with an attachment it can be done something like below.
#using System.Net.Mail;
SmtpClient smtpClient = new SmtpClient(host, port);
MailMessage message = new MailMessage(from, to, subject, body);
Attachment attachment = new Attachment(#"H:\attachment.jpg");
message.Attachments.Add(attachment);
System.Net.NetworkCredential SMTPUserInfo = new System.Net.NetworkCredential(username, password);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = SMTPUserInfo;
smtpClient.Send(message);
You can also do it without the authentication bit depending on your email server.
C# code to send email through Outlook; no security warnings occur.
var outlook = new ApplicationClass();
MailItem mailItem = (MailItem)outlook.Session.Application.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Display(false);

Categories