Microsoft Outlook adding Hyperlink to Email C# - c#

When sending an e-mail using Microsoft Outlook I want to be able to send a hyperlink of file locations and websites in the body of the e-mail the body in my code is oMsg.Body. Any help would be greatly appreciated.
private void button13_Click(object sender, EventArgs e)
{
//Send Routing and Drawing to Dan
// Create the Outlook application by using inline initialization.
Outlook.Application oApp = new Outlook.Application();
//Create the new message by using the simplest approach.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add a recipient
Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("email-address here");
oRecip.Resolve();
//Set the basic properties.
oMsg.Subject = textBox1.Text + " Job Release";
oMsg.Body = textBox1.Text + " is ready for release attached is the Print and Routing";
//Send the message. 6
oMsg.Send();
//Explicitly release objects.
oRecip = null;
oMsg = null;
oApp = null;
MessageBox.Show("Print and Routing Sent");
}

From MSDN, looks like you can set the BodyFormat to olFormatHTML and use the HTMLBody property:
oMsg.BodyFormat = olFormatHTML; // <-- Probably dont need this
oMsg.HTMLBody = "<HTML><BODY>Enter the message text here.</BODY></HTML>";
From the HTMLBody page, it looks like it sets the BodyFormat for you if you use the HTMLBody property, so you should be able to skip setting it.

Using HTML for the Body instead of plain text will allow you to include markup for hyperlinks:
oMsg.HTMLBody = "<html><body>";
oMsg.HTMLBody += textBox1.Text + " is ready for release attached is the Print and Routing";
oMsg.HTMLBody += "<p><a href='http://website.com'>Web Site</a></p></body></html>";
EDIT: Changed Body property to HTMLBody property.

Related

Outlook VSTO Add-In: Can not resolve recipientname

I'm programming an outlook add-in.
I want to modify the mail before it gets sent. Therefore I have registered me for an event before the email gets sent. I can modify it but when I m trying to change the recipient of the mail (so mail.To) it gives me an error (not while my code is running but when outlook tries to sent the mail).
Error says: '...Can not resolve the receivername' (i have translated it so it is not the real error text but close to it)
Here is my code:
void Application_ItemSend(object item, ref bool cancel)
{
if (item is Outlook.MailItem mail)
{
var to = mail.To;
var body = mail.Body;
var editedBody = to + "#" + body;
mail.Body = editedBody;
mail.To = #"<another email>";
}
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
//Register the new event
Globals.ThisAddIn.Application.ItemSend += Application_ItemSend;
}
You are resetting all To recipients. Is that what you really want to do? Try to use MailItem.Recipients.Add (retuns Recipient object) followed by Recipient.Resolve.
You are also setting the plain text Body property wiping out all formatting. Consider using HTMLBody instead, just keep in mind that two HTML strings must be merged rather than concatenated to produce valid HTML.
You need to cancel the action by setting the cancel parameter to true and schedule re-sending operation with a new email address. A timer which fires the Tick event on the main thread can help with that task.
Also you may consider making a copy of the email, changing recipients (do any changes on the copy) and submit it. In that case you will have to differentiate such messages and skip them in the ItemSend event handler. To get that working you may use UserProperties.
Got it working:
var to = string.Empty;
mail.Recipients.ResolveAll();
foreach (Outlook.Recipient r in mail.Recipients)
{
to += r.Address + ";";
}
if (to.Length > 0)
to = to.Substring(0, to.Length - 1);
mail.Body = to + "#" + mail.Body;
//Modify receiver
mail.To = string.Empty;
Outlook.Recipient recipient = mail.Recipients.Add("<email>");
recipient.Resolve();

Changing the sender address to default server in Outlook Object Mail

I have the following code to send emails automatically when looping through data retrieved from db:
public void sendMailV2(string subject, string body, string emailAddress)
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Get the NameSpace and Logon information.
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Alternate logon method that uses a specific profile.
// TODO: If you use this logon method,
// change the profile name to an appropriate value.
//oNS.Logon("YourValidProfile", Missing.Value, false, true);
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set the subject.
oMsg.Subject = subject;
// Set HTMLBody.
oMsg.HTMLBody = body;
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// TODO: Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(emailAddress);
oRecip.Resolve();
// Send.
oMsg.Send();
// Log off.
oNS.Logoff();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oNS = null;
oApp = null;
}
However, I want the emails to be sent from the server, not my own outlook. I have the username and password for the server(someserver#serving.com) but I can't figure out how and where to implement them.
I would appreciate any help.
First of all, there is no need to create a new Application instance if you need to send multiple emails. You may consider moving the following lines of code outside of the method and create the Application instance at the global scope.
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
If you have got another accounts configured in Outlook, you can use the SendUsingAccount property of the MailItem class which allows to set an Account object that represents the account under which the MailItem is to be sent.
If you don't have the required account configured in Outlook you may consider using the BCL classes for getting the job done. See How to send email from C# for more information.

Create multiple Outlook emails from C#

I'm new to C#. I've found how to create an outlook email from C#:
// Create a new MailItem.
Outlook._MailItem oMsg1;
oMsg1 = oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg1.To = "amine#gmail.com";
oMsg1.Subject = "Test Subject";
oMsg1.Body = "test Body";
Outlook.Attachments oAttachs1 = oMsg1.Attachments;
// Add an attachment
string sSource1 = "C:\\testFile.xls";
Outlook.Attachment oAttach1;
oAttach1 = oAttachs1.Add(sSource1);
oMsg1.Display(true);
oApp = null;
oMsg1 = null;
oAttach1 = null;
oAttachs1 = null;
But I want to create multiple emails at the same time. So Outlook will display multiple email windows.
I tried a for loop to create multiple mailItem but this didn't work. Outlook displays only the first email.
Any idea ? Thanks!
Use oMsg1.Display(false);
When set to True, oMsg1.Display(true) means Outlook creates a 'Modal' window, meaning it freezes that particular email until it is sent or discarded.

sending inline MHTML

I was wondering if it is possible through the .NET 2.0 MailMessage object to send an inline MHTML file that is created on the fly.
By inline I mean: It should be sent in a way that the user can see it, once he opens the email, without having to open/download the attachment.
It's a bit tricky, but yes, you can do it. In fact MailMessage class is nothing more than a wrapper above the system's CDO.Message class which can do the trick.
Also you can use AlternateView functionality, it's more simple:
MailMessage mailMessage = new MailMessage("me#me.com"
,"me#me.com"
,"test"
,"");
string ContentId = "wecandoit.jpg";
mailMessage.Body = "<img src=\"cid:" + ContentId + "\"/>";
AlternateView av = AlternateView.CreateAlternateViewFromString(mailMessage.Body
,null
,MediaTypeNames.Text.Html);
LinkedResource lr = new LinkedResource(#"d:\Personal\My Pictures\wecandoit.jpg");
lr.ContentId = ContentId;
lr.ContentType.Name = ContentId;
lr.ContentType.MediaType = "image/jpeg";
av.LinkedResources.Add(lr);
mailMessage.AlternateViews.Add(av);
SmtpClient cl = new SmtpClient();
cl.PickupDirectoryLocation = #"c:\test";
cl.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
cl.Send(mailMessage);
(jdecuyper -- thanks for the plug, as I wrote aspNetEmail).
You can do this with aspNetEmail. You can replace the entire contents of the email message with your MHT.
You can't do this with System.Net.Mail, but if you want to go the commerical route, pop me an email at dave#advancedintellect.com and I'll show you how this can be done.
If you want to go an open source route, there is probably some SMTP code on codeproject that you could modify to do this. Basically, you would inject your contents into the DATA command of the SMTP process.
One thing to note: If your MHT document has embedded scripts, flash, activeX objects or anything that may be blocked by the mail client, it probably won't render the same as what you are seeing in the browser.
Are you trying to add some images to an html email?
To accomplish this you will need to embed the images inside your email. I found a tutorial to accomplish it in a few lines of code. You can also buy the aspnetemail assembly. It has always helped me a lot to send emails with embedded images, they also have an excellent support team if anything goes wrong.
Keep in mind that embedding images makes your email heavier, but nicer :)
It is possible via CDO.Message (it is necessary add to project references COM library "Microsoft CDO for Windows 2000 Library"):
protected bool SendEmail(string emailFrom, string emailTo, string subject, string MHTmessage)
{
string smtpAddress = "smtp.email.com";
try
{
CDO.Message oMessage = new CDO.Message();
// set message
ADODB.Stream oStream = new ADODB.Stream();
oStream.Charset = "ascii";
oStream.Open();
oStream.WriteText(MHTmessage);
oMessage.DataSource.OpenObject(oStream, "_Stream");
// set configuration
ADODB.Fields oFields = oMessage.Configuration.Fields;
oFields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = CDO.CdoSendUsing.cdoSendUsingPort;
oFields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpAddress;
oFields.Update();
// set other values
oMessage.MimeFormatted = true;
oMessage.Subject = subject;
oMessage.Sender = emailFrom;
oMessage.To = emailTo;
oMessage.Send();
}
catch (Exception ex)
{
// something wrong
}
}
It is possible via CDO.Message (it is necessary add to project references COM library "Microsoft CDO for Windows 2000 Library"):
protected bool SendEmail(string emailFrom, string emailTo, string subject, string MHTmessage)
{
string smtpAddress = "smtp.email.com";
try
{
CDO.Message oMessage = new CDO.Message();
// set message
ADODB.Stream oStream = new ADODB.Stream();
oStream.Charset = "ascii";
oStream.Open();
oStream.WriteText(MHTmessage);
oMessage.DataSource.OpenObject(oStream, "_Stream");
// set configuration
ADODB.Fields oFields = oMessage.Configuration.Fields;
oFields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value = CDO.CdoSendUsing.cdoSendUsingPort;
oFields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value = smtpAddress;
oFields.Update();
// set other values
oMessage.MimeFormatted = true;
oMessage.Subject = subject;
oMessage.Sender = emailFrom;
oMessage.To = emailTo;
oMessage.Send();
}
catch (Exception ex)
{
// something wrong
}
}

Help! Sending HTML e-mail via C# - Windows Mobile Outlook reads it as gibberish

I have a script that sends an e-mail as both plain text and HTML, and it works fine for most e-mail readers including Outlook and Gmail. However, when reading the message on a Windows Mobile smartphone, the output is:
PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDMuMiBGaW5hbC8vRU4i Pg0KPEhUTUw+DQo8SEVBRD4NCiAgICA8TUVUQSBIVFRQLUVRVUlWPSJDb250ZW50LVR5cGUi IENPTlRFTlQ9InRleHQvaHRtbDtjaGFyc2V0PWlzby04ODU5LTEiPg0KICAgIDxUSVRMRT5Z b3VyIE1lZ2Fwb255IFBhc3N3b3JkIC0gTWVnYXBvbnkgLSBEaXNjb3ZlciB0aGUgbmV4dCBi aWcgdGhpbmc8L1RJVExFPg0KICAgIDxTVFlMRSBUWVBFPSJ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lh bCIgQ09MT1I9IiM5OTAwMDAiPk1lZ2Fwb255LmNvbTwvRk9OVD48L0E+DQogICAgICAgIDxG T05UIFNJWkU9IjQiIEZBQ0U9IkFyaWFsIj4NCiAgICAgICAgICAgIHRvIGFjY2VzcyB5b3Vy IGFjY291bnQuDQogICAgICAgICAgICA8QlI+DQogICAgICAgICAgICA8QlI+DQogICAgICAg ICAgICBUaGFuayB5b3UgZm9yIHlvdXIgc3VwcG9ydCBvZiBNZWdhcG9ueSBhbmQgaW5kZXBl bmRlbnQgbXVzaWMhPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICAgICAgU2luY2Vy ZWx5LDxCUj4NCiAgICAgICAgICAgIDxCUj4NCiAgICAgICAgICAgIFRoZSBNZWdhcG9ueSBU ZWFtPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICAgICAgPEJSPg0KICAgICAgICA8 L0ZPTlQ+PEZPTlQgU0laRT0iMiIgRkFDRT0iQXJpYWwiPipUaGlzIGlzIGFuIGF1dG9tYXRl ZCBtZXNzYWdlLiBQbGVhc2UgZG8gbm90IHJlcGx5LjwvRk9OVD4NCjwvQk9EWT4NCjwvSFRN TD4NCg==
The correct output should be: Click here to see
The code is:
SmtpClient mC = new SmtpClient(ConfigurationManager.AppSettings["smtpServer"]);
NetworkCredential nC = new NetworkCredential(ConfigurationManager.AppSettings["smtpUsername"], ConfigurationManager.AppSettings["smtpPassword"]);
mC.UseDefaultCredentials = false;
mC.Credentials = nC;
MailAddress mFrom = new MailAddress("noreply#megapony.com", "Megapony");
MailAddress mTo = new MailAddress(forgotpwemail.Text);
MailMessage mMsg = new MailMessage(mFrom, mTo);
mMsg.IsBodyHtml = false;
mMsg.Subject = "Your Megapony Password";
mMsg.Body = getForgotPWBodyPlain(result);
System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/html");
AlternateView alternate = AlternateView.CreateAlternateViewFromString(getForgotPWBody(result), mimeType);
mMsg.AlternateViews.Add(alternate);
try
{
mC.Send(mMsg);
pnlpwform.Visible = false;
pnlSuccess.Visible = true;
}
catch (Exception)
{
pnlResponse.Visible = true;
}
mMsg.Dispose();
Please help!
Thanks,
Paul
I would say it's a combination of the content-type and the the image that's causing the issue. The link you provided showed a nice gif with a Megapony logo, yet the content-type is set to text only. Because of this, the bits that make up the gif is being treated as a series of text characters.
This would be a good place to start: http://www.systemnetmail.com/faq/3.1.3.aspx

Categories

Resources