I'm looking for a way to open a New mail in Outlook window.
I need programically fill: from, to, subject, body information, but leave this new mail window open so user can verify content / add something then send as normal Outlook msg.
Found that:
Process.Start(String.Format(
"mailto:{0}?subject={1}&cc={2}&bcc={3}&body={4}",
address, subject, cc, bcc, body))
But there is no "From" option (my users have more than one mailbox...)
Any advice(s) ?
I've finally resolved the issue.
Here is piece of code resolving my problem (using Outlook interops)
Outlook.Application oApp = new Outlook.Application ();
Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem ( Outlook.OlItemType.olMailItem );
oMailItem.To = address;
// body, bcc etc...
oMailItem.Display ( true );
Here is what i have tried. It's working as expected.
This application Adding Recipients, adding cc and adding subject and opening a new mail window.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using Outlook = Microsoft.Office.Interop.Outlook;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSendMail_Click(object sender, EventArgs e)
{
try
{
List<string> lstAllRecipients = new List<string>();
//Below is hardcoded - can be replaced with db data
lstAllRecipients.Add("sanjeev.kumar#testmail.com");
lstAllRecipients.Add("chandan.kumarpanda#testmail.com");
Outlook.Application outlookApp = new Outlook.Application();
Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMailItem.GetInspector;
// Thread.Sleep(10000);
// Recipient
Outlook.Recipients oRecips = (Outlook.Recipients)oMailItem.Recipients;
foreach (String recipient in lstAllRecipients)
{
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(recipient);
oRecip.Resolve();
}
//Add CC
Outlook.Recipient oCCRecip = oRecips.Add("THIYAGARAJAN.DURAIRAJAN#testmail.com");
oCCRecip.Type = (int)Outlook.OlMailRecipientType.olCC;
oCCRecip.Resolve();
//Add Subject
oMailItem.Subject = "Test Mail";
// body, bcc etc...
//Display the mailbox
oMailItem.Display(true);
}
catch (Exception objEx)
{
Response.Write(objEx.ToString());
}
}
}
You can't do this with mailto. Either your client will have to select the account they are sending from, which defaults to their default account or you will have to provide a mail form and set the headers when you send the e-mail.
Related
This question already has answers here:
send email in c#
(7 answers)
Closed 3 years ago.
I want to get help with how to send the console output via email on a click button function in my program.
The variable textBox2.Text contains the text that is being printed out to the console and I want this text to be send automatically on the (button1_Click_1) function.
I have found some solutions on somewhat similar questions but none of them seem to work, I hope I can find a solution here.
My code:
private void textBox2_TextChanged(object sender, EventArgs e)
{
Console.WriteLine(textBox2);
}
private void button1_Click_1(object sender, EventArgs e)
{
//Sending email function with the console output that is being printed from (textBox2.Text) should be here.
Taskbar.Show();
System.Windows.Forms.Application.Exit();
}
Microsoft recommends that MailKit and MimeKit libraries be used for sending emails from C# applications.
Here is the working code snippet in C# for sending an email:
// File name: SendMail.cs
using System;
using MailKit.Net.Smtp;
using MailKit;
using MimeKit;
namespace SendMail {
class Program
{
public static void Main (string[] args) {
using (var client = new SmtpClient ()) {
// Connect to the email service (Accept ssl certificate)
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.Connect ("smtp.friends.com", 587, false);
// Optional step: Send user id, password, if the server requires authentication
client.Authenticate ("emailID", "emailPassword");
// Construct the email message
var message = new MimeMessage();
message.From.Add (new MailboxAddress ("Sender's Name", "sender-email#example.com"));
message.To.Add (new MailboxAddress ("Receiver's Name", "receiver-email#example.com"));
message.Subject = "Automatic email from the application";
message.Body = new TextPart ("plain") { Text = #"Hello Customer, Happy new year!"};
// Send the email
client.Send (message);
// Close the connection with the email server
client.Disconnect (true);
}
}
}
}
More information:
https://github.com/jstedfast/MailKit
I'm currently building a plugin for Outlook using C#, but when I create new email item in the thread, if I add attachments to email, my Outlook is blocking the user interface (freezing) until email created.
If I don't add attachments that not blocking the user interface Outlook.
So how can I fix that (not blocking the user interface outlook)?
This my code:
In Ribbon.cs, I have function button click:
private void button2_Click(object sender, RibbonControlEventArgs e){
Globals.ThisAddIn.CheckProcessEmail();
}
and function CheckProcessEmail, I create new Thread:
public void CheckProcessEmail(){
Thread threadCheckTest = new Thread(CheckTest);
threadCheckTest.Start();
}
public static void CheckTest(){
Outlook.Application application = Globals.ThisAddIn.Application;
Outlook.MailItem item = application.CreateItem((Outlook.OlItemType.olMailItem));
Outlook.MAPIFolder sentBox = (Outlook.MAPIFolder)Globals.ThisAddIn.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
Outlook.MailItem email = (Outlook.MailItem)sentBox.Items.Add();
email.Subject = "Send Test";
email.HTMLBody = "<div class=WordSection1><p class=MsoNormal>sad<o:p></o:p></p></div><b>Strong</b><h1>Hello</h1>";
email.To = "a#test.com;b#test.com;c#test.com";
email.BCC = "cc#test.com";
email.Attachments.Add(#attachmentPath, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
email.Save();
}
I am attempting to program a DataGridHyperlinkColumn which contains user's emails to send a new email through outlook when clicking on the address. For now I am just using a test email instead of getting the contents of the column, but this is what I have so far;
<DataGridHyperlinkColumn Header="Email" Binding="{Binding Email}">
<DataGridHyperlinkColumn.ElementStyle>
<Style>
<EventSetter Event="Hyperlink.Click" Handler="OnEmailHyperlinkClick"/>
</Style>
</DataGridHyperlinkColumn.ElementStyle>
</DataGridHyperlinkColumn>
Then the handler in C#;
private void OnEmailHyperlinkClick(object sender, RoutedEventArgs e)
{
string subject = "My subject";
string emailTag = string.Format("mailto:someone#test.com?subject={0}", subject);
System.Diagnostics.Process.Start(emailTag);
}
At the moment this is providing strange behaviour. First of all it opens a new instance of Google Chrome. Nothing to do with Outlook at at all. It then crashes saying;
Cannot locate resource 'addressbook/someone#test.com'
It's almost as if this event is actually being handled elsewhere, but I am lamost certain it isn't. Has anyone experienced this before?
All that your solution does is tells windows to try to start a new process using the provided string.
You need to specify that you want it to use outlook.
Add the Microsoft.Office.Interop.Outlook reference to your project (make sure it's the correct version)
Then try something like this:
public static void OnEmailHyperlinkClick(object sender, RoutedEventArgs e)
{
try
{
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
MailItem msg = (MailItem)oApp.CreateItem(OlItemType.olMailItem);
msg.Subject = "My subject";
msg.Body = "My Message Body";
Recipients recipients = (Recipients)msg.Recipients;
Recipient recipient = (Recipient)recipients.Add("someone#test.com");
recipient.Resolve();
msg.Display(); // If you want to have the email displayed for the user to send
// Otherwise
msg.Send();
recipient = null;
recipients = null;
msg = null;
oApp = null;
}
catch (Exception ex)
{
}
}
I'm working on a small project of mine and I'm not sure if what I am trying to do is possible on a web based solution.
And right now it's setup like this, a user post something and that date he posted in the database. What I want to do is if the user doesn't post another thing within 7 days I want to send them an email saying they are "late" or something similar to that.
I know how to send a email in asp.net as my user can request a new password / they need to verify their email. I just don't know how to set it up like I want above ( IF that even is possible )
You need a separate process that checks for, and then sends, the emails. You won't be able to do it in the web application itself, but some kind of service would do it.
This service would just need to periodically check your database for users and the last date they posted. If it's more than 7 days, send that email off.
Remember to record that the email has been sent and check this when determining what emails to send, otherwise you'll get an email sent every time the service checks the database, which might frustrate the user a bit!
sending email in asp is simple. its a code i did before that check if you want to send a file too:
for working with time you have to work with timeSpan and dateTime
its from example in stackoverflow:
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
you have to check if this value is bigger than 7
so code for sending mail is like below but you have to optimize it for your own:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
MailMessage mail = new MailMessage();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
lblmessage.Text ="";
mail.To.Add(txtto.Text.Trim());
mail.From = new MailAddress(txtfrom.Text.Trim());
mail.Subject = txtsubject.Text.Trim();
mail.Body = txtbody.Text.Trim();
mail.IsBodyHtml = true;
if (uploader.HasFile)
{
string filename = uploader.PostedFile.FileName;
string filepath=Server.MapPath("uploads//"+filename);
uploader.SaveAs(filepath);
Attachment attach = new Attachment(filepath);
attach.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
mail.Attachments.Add(attach);
}
SmtpClient client = new SmtpClient();
client.Host = "mail.youdomain.com";
client.Credentials = new System.Net.NetworkCredential("email username=info#yourdomain.com", "email passowrd");
client.Send(mail);
lblmessage.Text = "sent with success";
}
catch (Exception ex)
{
lblmessage.Text = ex.Message;
}
}
}
I have a program that is using Outlook to send messages with attachments. It is working ok, sending emails with attachments but in outbox there is no attachment in the message. When somebody receive the message the attachment is visible but in outbox not.
Here is some code:
Outlook.MailItem mail = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mail.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
int iAttachType = (int)Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue;
mail.Attachments.Add(Application.StartupPath+"/"+attachment, iAttachType, null, attachment);
mail.To = email;
mail.Subject = "Something";
mail.Body = "Some body";
mail.Send();
Before this I use:
private Outlook.Application outlookApp;
private Outlook._NameSpace outlookNameSpace;
private Outlook.MAPIFolder outbox;
and
outlookApp = new Outlook.Application();
outlookNameSpace = outlookApp.GetNamespace("MAPI");
outlookNameSpace.Logon(null, null, false, false);
outbox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox);
My outlook program is connected with Microsoft Exchange Serwer. When I was using an application written in C++ it saved attachment in messages in outbox.
Thx for help!
You could be working with an old version of the outlook item.
This can happen if you keep references to your mail items, rec-patterns, inspectors and some other types [that I now forgot] longer than you need them.
Your reference will often point to the old version of the item and keeping it can also prevent you from getting a reference to the updated one (the one with the attachment), even when events (Folder.BeforeItemMove) are triggered.
Also, have you tried if mail.Save() would do anything for you?
This is what I use as soon as I am done with an item.
public static void NullAndRelease(object o)
{
if (o == null) {
return;
}
try {
int releaseResult = 0;
do {
releaseResult = System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
} while (releaseResult >= 0);
} catch {
} finally {
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
The catch has no message and is not important in my case. It is there if someone would pass in a reference that leads to something other than a com object. You can also try FinalReleaseComObject(o).