string email ="sample#gmail.com";
attachment = path + "/" + filename;
Application.OpenURL ("mailto:" +
email+"
?subject=EmailSubject&body=EmailBody"+"&attachment="+attachment);
In the above code, attachment isn't working. Is there any other alternative to add attachments using a mailto: link in C#?
mailto: doesn't officially support attachments. I've heard Outlook 2003 will work with this syntax:
<a href='mailto:name#domain.com?Subject=SubjTxt&Body=Bod_Txt&Attachment=""C:\file.txt"" '>
Your problem has already been answered:
c-sharp-mailto-with-attachment
You can use the System.Net.Mail which has the MailMessage.Attachments Property. Something like:
message.Attachments.Add(new Attachment(yourAttachmentPath));
OR
You can try like this:
using SendFileTo;
namespace TestSendTo
{
public partial class Form1 : Form
{
private void btnSend_Click(object sender, EventArgs e)
{
MAPI mapi = new MAPI();
mapi.AddAttachment("c:\\temp\\file1.txt");
mapi.AddAttachment("c:\\temp\\file2.txt");
mapi.AddRecipientTo("person1#somewhere.com");
mapi.AddRecipientTo("person2#somewhere.com");
mapi.SendMailPopup("testing", "body text");
// Or if you want try and do a direct send without displaying the
// mail dialog mapi.SendMailDirect("testing", "body text");
}
}
}
The above code uses the MAPI32.dll.
Source
It probably won't attach the document because you are at the liberty
of the email client to implement the mailto protocol and include
parsing for the attachment clause. You may not know what mail client
is installed on the PC, so it may not always work - Outlook certainly
doesn't support attachments using mailto.
A better way to handle this is to send the mail on the server using System.Net.Mail.Attachment.
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}", ex.ToString());
}
data.Dispose();
}
Related
I set up my outlook Office 365 account and I want to retrieve the emails from my outlook mailbox, earlier we were using Exchange Service in our code, but now we can't use the Exchange service anymore due to EWS his no longer available in microsoft.
Could you please help me how can I retrieve my emails in outlook office 365 account.
I am attaching a sample code that I have created but I am not able to read the emails.
In the below code, i tried to retrieve email through IMAP4 protocol server.
When i run the code, i get this error - ReceiveOutlookMail.exe' has exited with code 0 (0x0).
class Program
{
// Generate an unqiue email file name based on date time
static string _generateFileName(int sequence)
{
DateTime currentDateTime = DateTime.Now;
return string.Format("{0}-{1:000}-{2:000}.eml",
currentDateTime.ToString("yyyyMMddHHmmss", new CultureInfo("en-US")),
currentDateTime.Millisecond,
sequence);
}
static void Main(string[] args)
{
try
{
// Create a folder named "inbox" under current directory
// to save the email retrieved.
string localInbox = string.Format("{0}\\inbox", Directory.GetCurrentDirectory());
// If the folder is not existed, create it.
if (!Directory.Exists(localInbox))
{
Directory.CreateDirectory(localInbox);
}
// Hotmail/MSN IMAP4 server is "imap-mail.outlook.com"
//MailServer oServer = new MailServer("imap-server-name",
// "liveid#hotmail.com", "yourpassword", ServerProtocol.Imap4);
// For office 365 user, please change server to:
MailServer oServer = new MailServer("imap-server-name",
"test#gmail.com", "password", ServerProtocol.Imap4);
// Enable SSL connection.
oServer.SSLConnection = true;
// Set 993 SSL port
oServer.Port = 993;
MailClient oClient = new MailClient("TryIt");
oClient.Connect(oServer);
// retrieve unread/new email only
oClient.GetMailInfosParam.Reset();
oClient.GetMailInfosParam.GetMailInfosOptions = GetMailInfosOptionType.NewOnly;
MailInfo[] infos = oClient.GetMailInfos();
Console.WriteLine("Total {0} unread email(s)\r\n", infos.Length);
for (int i = 0; i < infos.Length; i++)
{
MailInfo info = infos[i];
Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
info.Index, info.Size, info.UIDL);
// Receive email from IMAP4 server
Mail oMail = oClient.GetMail(info);
Console.WriteLine("From: {0}", oMail.From.ToString());
Console.WriteLine("Subject: {0}\r\n", oMail.Subject);
// Generate an unqiue email file name based on date time.
string fileName = _generateFileName(i + 1);
string fullPath = string.Format("{0}\\{1}", localInbox, fileName);
// Save email to local disk
oMail.SaveAs(fullPath, true);
// mark unread email as read, next time this email won't be retrieved again
if (!info.Read)
{
oClient.MarkAsRead(info, true);
}
// if you don't want to leave a copy on server, please use
// oClient.Delete(info);
// instead of MarkAsRead
}
// Quit and expunge emails marked as deleted from IMAP4 server.
oClient.Quit();
Console.WriteLine("Completed!");
}
catch (Exception ep)
{
Console.WriteLine(ep.Message);
}
}
}
}
MailRepository rep = new MailRepository("imap.mail.yahoo.com", 993, true, #"xxxxx#yahoo.com", "*******");
foreach (Message email in rep.GetUnreadMails("Inbox"))
{
//Console.WriteLine(string.Format("<p>{0}: {1}</p><p>{2}</p>", email.From, email.Subject, email.BodyHtml.Text));
Console.WriteLine(email.From);
Console.WriteLine(email.Subject);
Console.WriteLine(email.BodyHtml.Text);
if (email.Attachments.Count > 0)
{
foreach (MimePart attachment in email.Attachments)
{
Console.WriteLine(string.Format("<p>Attachment: {0} {1}</p>", attachment.ContentName, attachment.ContentType.MimeType));
}
}
}
Above is my code, which is used to read mail content. It's working fine when i tryed for gmail port, but while going for yahoo or some other. It's not allowing me to read the mail throwing exception. Is there any other source . Please guide me
First, check your credentials are correct.
Second, put a try catch in the constructor to see if you can get more info about the unhandled exception:
public MailRepository(string mailServer, int port, bool ssl, string login, string password)
{
try {
if (ssl) {
Client.ConnectSsl(mailServer, port);
}
else {
Client.Connect(mailServer, port);
}
Client.Login(login, password);
}
catch(Exception ex)
{
//Check the exception details here
}
}
Third, the origin of the MailRepository class appears to be from here that uses the Imap4Client implementation which others have complained doesn't work with Yahoo:
Connecting to yahoo email with IMAP4 MailSystem.NET
The accepted answer recommends using ImapX 2 - crossplatform IMAP library for .NET to handle GMail, Yahoo, etc.
I have a WinForms app that at the click of a button automatically produces an Outlook mail as follows:
public static void CreateOutlookEmail(string pFileName, string pCaseFolder, string pEmail, string pSubject, string pMessage)
{
try
{
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = pSubject;
mailItem.To = pEmail;
mailItem.Body = pMessage;
mailItem.Importance = Outlook.OlImportance.olImportanceNormal;
mailItem.Display(false);
string fileDetails = pCaseFolder + "\\" + pFileName + #".eml";
mailItem.SaveAs(fileDetails);
}
catch (Exception eX)
{
throw new Exception("cDocument: Error occurred trying to Create an Outlook Email"
+ Environment.NewLine + eX.Message);
}
}
The code succesfully opens a new Outlook email, and populates it with the details sent into the method e.g. email address, subject and the body of the message.
Also when I locate the folder (sent in as a paramater) I can see the email document has been saved.
The issue is, that when I open the email from the folder, the email document is totaly blank ii.e. no email address, subject or message.
What am I doing wrong?
Your code is fine. Just use extension ".msg" instead of ".eml". Also the eml format does not exist under Outlook.OlSaveAsType
My environments are
Server Machine: DocuShare Server 6
Client Machine: Windows XP where DocuShare client 6, DocuShare outlook client 3, MS outlook 2007 and our C# application are installed.
We have a C# application to download mail message from DocuShare server using DocuShare API.
The application successfully downloads docushare mail messages as MSG file. But when the mail message has attachment with long name (in my case the attachment file name is
"New Tzunami Outlook Attachment Extractor User Guide 20100902.docx"), the application throws Windows Socket error while downloading. If the attachment file name is short, mail messages are downloaded successfully.
Here are the codes:
private void btnDownloadMails_Click(object sender, EventArgs e)
{
MailArgument mailArg = new MailArgument();
mailArg.server = textServer.Text;
mailArg.user = textUser.Text;
mailArg.password = textPwd.Text;
DownloadMailAsMsg(mailArg);
}
void DownloadMailAsMsg(object s)
{
MailArgument mailArg = s as MailArgument;
long status = 0;
DSServerMap.Server dsserver = new DSServerMap.Server();
if (!SelectMappedServer(ref dsserver, mailArg.server))
return;
dsserver.DocuShareAddress = mailArg.server;
dsserver.UserName = mailArg.user;
dsserver.Password = mailArg.password;
dsserver.Domain = "DocuShare";
status = dsserver.Logon();
if (status == 0)
{
IItemObj objParentItem;
string[] emailHan = { "MailMessage-2919", "MailMessage-2924", "MailMessage-2925", "MailMessage-2926", "MailMessage-2926", "MailMessage-15", "MailMessage-30", "MailMessage-31" };
foreach (string handnum in emailHan)
{
objParentItem = (IItemObj)dsserver.CreateObject(handnum);
DSGATEWAYLib.IGatewayHandler gateway = (DSGATEWAYLib.IGatewayHandler)dsserver.Open();
objParentItem.AttachGateway(gateway, true);
objParentItem.Name = #"D:\emtest\" + handnum + ".msg";
int flag = objParentItem.DSDownload(0);
}
}
}
Where I stuck is at the line: int flag = objParentItem.DSDownload(0); while downloading email which have attachment file named "New Tzunami Outlook Attachment Extractor User Guide 20100902.docx".
For checking, we trimmed the attachment file name to "ANew Tzunami OutAttachmen 01.docx" but we still got the same error.
The code objParentItem.DSDownload(0) return -300 value and at the same time DocuShare error dialog box pops up with following message
"Winsock error 123"
When DsAxess console is used to download the same mail message, we got the same WinSock error, so nothing can be done;).
We used WorldClient mail application for sending emails. We sent email with the attachment having "ANew Tzunami OutAttachmen 01.docx" file name using WorldCLient, which we failed to download. For the sake of tesing we used another application to send the email with the same attachment. This time we used MS word to send email with the same attachment and we succeeded downloading email using C# app and DsAxess console as well.
If you have anything about this, please share with us.
thank you.
Prakash
Currently I am using the below method to open the users outlook email account and populate an email with the relevant content for sending:
public void SendSupportEmail(string emailAddress, string subject, string body)
{
Process.Start("mailto:" + emailAddress + "?subject=" + subject + "&body="
+ body);
}
I want to however, be able to populate the email with an attached file.
something like:
public void SendSupportEmail(string emailAddress, string subject, string body)
{
Process.Start("mailto:" + emailAddress + "?subject=" + subject + "&body="
+ body + "&Attach="
+ #"C:\Documents and Settings\Administrator\Desktop\stuff.txt");
}
However this does not seem to work.
Does anyone know of a way which will allow this to work!?
Help greatly appreciate.
Regards.
If you want to access the default email client then you can use MAPI32.dll (works on Windows OS only).
Take a look at the following wrapper:
http://www.codeproject.com/KB/IP/SendFileToNET.aspx
Code looks like this:
MAPI mapi = new MAPI();
mapi.AddAttachment("c:\\temp\\file1.txt");
mapi.AddAttachment("c:\\temp\\file2.txt");
mapi.AddRecipientTo("person1#somewhere.com");
mapi.AddRecipientTo("person2#somewhere.com");
mapi.SendMailPopup("testing", "body text");
// Or if you want try and do a direct send without displaying the mail dialog
// mapi.SendMailDirect("testing", "body text");
mailto: doesn't officially support attachments. I've heard Outlook 2003 will work with this syntax:
<a href='mailto:name#domain.com?Subject=SubjTxt&Body=Bod_Txt&Attachment=""C:\file.txt"" '>
A better way to handle this is to send the mail on the server using System.Net.Mail.Attachment.
public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"jane#contoso.com",
"ben#contoso.com",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString() );
}
data.Dispose();
}
Does this app really need to use Outlook? Is there a reason for not using the System.Net.Mail namespace?
If you really do need to use Outlook ( and I would not recommend it because then you're basing your app on 3rd party dependencies that are likely to change) you will need to look into the Microsoft.Office namespaces
I'd start here:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.aspx
Try this
var proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = string.Format("\"{0}\"", Process.GetProcessesByName("OUTLOOK")[0].Modules[0].FileName);
proc.StartInfo.Arguments = string.Format(" /c ipm.note /m {0} /a \"{1}\"", "someone#somewhere.com", #"c:\attachments\file.txt");
proc.Start();