Sending the Html in body with meeting Invitation C# - c#

I have a requirement to send the meeting request with html body Tag.I have successfully send the meeting request it work perfectly.
Here is the ICS file format
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//A//B//EN
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
ORGANIZER;CN="Organizer":mailto:#FROM#
ATTENDEE;CN="Attendee";CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=
NEEDS-ACTION;RSVP=TRUE:mailto:#TO#
DTSTART:#DTSTART#
DTEND:#DTEND#
LOCATION:#LOCATION#
SUMMARY: Invitation for Meeting
TRANSP:OPAQUE
SEQUENCE:0
UID:#UID#
DTSTAMP:#CREATED-AT#
CREATED:#CREATED-AT#
LAST-MODIFIED:#CREATED-AT#
DESCRIPTION: #DESCRIPTION#
X-ALT-DESC;FMTTYPE=text/html: #X-ALT-DESC#
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR
I found some link to send the html link wiht X-ALT-DESC option but it not work for me
Send an Outlook Meeting Request with C#
Send an Outlook Meeting Request with C#
Send email to Outlook with ics meeting appointment
Send email to Outlook with ics meeting appointment
Here is the C# code to send the email with ICS file
filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Email/calenderInvitation.ics");
fileContent = System.IO.File.OpenText(filePath).ReadToEnd();
fileContent = fileContent.Replace("#TO#", receiver);
fileContent = fileContent.Replace("#FROM#", fromAddress.Address);
fileContent = fileContent.Replace("#LOCATION#", eventVenue);
fileContent = fileContent.Replace("#UID#", Guid.NewGuid().ToString().Replace("-", ""));
fileContent = fileContent.Replace("#CREATED-AT#", Convert.ToDateTime(meetingDate).ToString(TimeFormat));
fileContent = fileContent.Replace("#DTSTART#", Convert.ToDateTime(startTime).ToString(TimeFormat));
fileContent = fileContent.Replace("#DTEND#", Convert.ToDateTime(finishTime).ToString(TimeFormat));
filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Email/InvitationEmail.html");
fileInviationContent = System.IO.File.OpenText(filePath).ReadToEnd();
String body = AppendRedirectURl(fileInviationContent, callBackUrl);
fileContent = fileContent.Replace("#X-ALT-DESC#", body);
MailMessage message = new MailMessage();
// message.IsBodyHtml = true;
message.From = new MailAddress(fromAddress.Address);
message.To.Add(new MailAddress(receiver));
message.Subject = string.Format("{0} {1} # {2} {3} {4} {5} - {6}", "Invitation: ", meetingTypeName,
Convert.ToDateTime(meetingDate).ToString("dddd"), Convert.ToDateTime(startTime).ToString("MMMM"),
Convert.ToDateTime(startTime).ToString("yyyy"), startTime,
finishTime);
var iCalendarContentType = new ContentType("text/calendar; method=REQUEST");
var calendarView = AlternateView.CreateAlternateViewFromString(fileContent, iCalendarContentType);
calendarView.TransferEncoding = TransferEncoding.SevenBit;
message.AlternateViews.Add(calendarView);
await smtp.SendMailAsync(message);
Here is the Debugger response
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//A//B//EN
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
ORGANIZER;CN="Organizer":mailto:admin#wordflow.info
ATTENDEE;CN="Attendee";CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=
NEEDS-ACTION;RSVP=TRUE:mailto:anandjaisy#gmail.com
DTSTART:20171206T081500Z
DTEND:20171206T090000Z
LOCATION:asdasd
SUMMARY: Invitation for Meeting
TRANSP:OPAQUE
SEQUENCE:0
UID:b17f15326c5343ff98d76bf6092ed2b4
DTSTAMP:20171212T000000Z
CREATED:20171212T000000Z
LAST-MODIFIED:20171212T000000Z
DESCRIPTION: #DESCRIPTION#
X-ALT-DESC;FMTTYPE=text/html: <html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<br><br><br>
<form class="container">
<div class="form-group">
<label>Click on Accept or Decline to add event to your Email Calender </label>
</div>
<div class="form-group">
<label>Will you Attend the Meeting</label>
Yes
No
</div>
<div class="form-group text-center">
</div>
</form>
</body>
</html>
PRIORITY:5
CLASS:PUBLIC
END:VEVENT
END:VCALENDAR
It send the invitation but body is not been send

I found the solution at this link (visual basic) https://social.msdn.microsoft.com/Forums/en-US/2cd0dcff-7d6c-493e-bf49-87a3e3248d01/create-meeting-request-with-html-body-in-aspnet?forum=netfxnetcom
Basically, you add a second AlternateView. Below is how I did it. My "body" string has my html. I did notice that my meeting was broken in Outlook if I add "avCalendar" before "avHtmlBody". So I guess the order matters.
In my meetingRequestString, I removed the parts for DESCRIPTION and X-ALT-DESC.
MailMessage msg = new MailMessage(from, to);
var htmlContentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html);
var avHtmlBody = AlternateView.CreateAlternateViewFromString(body, htmlContentType);
msg.AlternateViews.Add(avHtmlBody);
string meetingRequestString = GetMeetingRequestString(from, to, subject, body, startTime, endTime);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
ct.Parameters.Add("method", "REQUEST");
ct.Parameters.Add("name", "meeting.ics");
AlternateView avCalendar = AlternateView.CreateAlternateViewFromString(meetingRequestString, ct);
msg.AlternateViews.Add(avCalendar);
client.Send(msg);

Related

c# Sending Email with Mailkit with an HTML template file that has images imbedded

I would like to send an email using MailKit by linking to an html template that has images imbedded, for the C# part I use this code :
var email = new MimeMessage();
var bodyBuilder = new BodyBuilder();
var image= bodyBuilder
.LinkedResources
.Add(#"E:\Hicham\MIMNESTHelper\image.jpg");
image.ContentId = MimeUtils.GenerateMessageId();
using (StreamReader SourceReader = System.IO.File.OpenText("E:\\Hicham\\MIMNESTHelper\\EmailTemplate.html"))
{
bodyBuilder.HtmlBody = SourceReader.ReadToEnd();
}
email.Body = bodyBuilder.ToMessageBody();
In my html template body, I have tried to add the cid to the attached image as such:
<div style="background-color:#000000;padding:1em;width:50%">
<center><img src='image.ContentId' /></center>
</div>
thanks
Hicham
I suggest that your html file have a placeholder that you can replace later.
<img src='cid:[img-src]' />
And in your code, replace the placeholder with the correct value:
bodyBuilder.HtmlBody = bodyBuilder.HtmlBody.Replace("[img-src]", image.ContentId);
email.Body = bodyBuilder.ToMessageBody();
Goodluck!

SmtpClient fails to send ical meeting invite when there's a period in Organizer's email

I am trying to send an Meeting Invite with C# and for some reason it will not be sent if the Organizer's email address has a period.
ORGANIZER;CN="John, Song":mailto:song.john#company.com
It will work if I remove the period in the email address
ORGANIZER;CN="John, Song":mailto:songjohn#company.com
My complete sample code is here.
public static void SendEmailString()
{
MailMessage msg = new MailMessage();
msg.From = new MailAddress("song#company.com", "Song");
msg.To.Add(new MailAddress("John#company.com", "John"));
msg.Subject = "CS Inquiry";
msg.Body = "TESTING";
string test = #"BEGIN:VCALENDAR
PRODID: -//Company & Com//Credit Inquiry//EN
VERSION:2.0
METHOD:REQUEST
BEGIN:VEVENT
ATTENDEE;CN=""John, Song"";ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:song#company.com
ATTENDEE;CN=""Lay, Sean"";ROLE=REQ-PARTICIPANT;RSVP=TRUE:MAILTO:lins#company.com
ORGANIZER;CN="John, Song":mailto:song.john#company.com
DTSTART:20171205T040000Z
DTEND:20171206T040000Z
LOCATION:New York
TRANSP:TRANSPARENT
SEQUENCE:0
UID:a16fbc2b-72fd-487f-adee-370dc349a2273asfdasd
DTSTAMP:20171027T215051Z
DESCRIPTION:Request for information regarding Test
SUMMARY:Summary
PRIORITY: 5
CLASS: PUBLIC
BEGIN:VALARM
TRIGGER:-PT1440M
ACTION: DISPLAY
DESCRIPTION:REMINDER
END:VALARM
END:VEVENT
END:VCALENDAR
";
SmtpClient sc = new SmtpClient("smtp.company.com");
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
ct.Parameters.Add("method", "REQUEST");
AlternateView avCal = AlternateView.CreateAlternateViewFromString(test, ct);
msg.AlternateViews.Add(avCal);
sc.Send(msg);
}
Anyone know why this is happening? I looked at the iCalendar spec and couldn't find anything about period being an illegal character in Organizer's email address.
Thanks!

EWS emails have base64 img tags encoded

Background context:
I'm using EWS Managed API 2.0 to connect to customer Outlook mailbox and process their emails into my application. I do not have control over what kind of emails the customers send, however part of the processing is maintaining the attachments and embedded images that are being sent.
My problem:
One of the users has sent an HTML type email with a base64 image as part of his signature. The Exchange Api gets the body of the email HTML encoded and part of the body, base64 images are encoded as well (converted the '+' sign to '& #43;'), which now breaks my application.
Question: Is there a way to retrieve the email body without having the base64 images encoded? As a workaround, right now I'm doing a string replace of '& #43;' to '+'.
This is part of the code I'm using to get the email body; The Assembly I'm using: Microsoft.Exchange.WebServices Version=15.0.0.0
var service = new ExchangeService(Exchange2010_SP2);
// rest of creating the service
var singleEmailView = new ItemView(1);
SearchFilter unreadEmailsFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
var emailResults = service.FindItems(WellKnownFolderName.Inbox, unreadEmailsFilter, singleEmailView);
if (emailResults.Items.Any())
{
var firstItem = emailResults.Items.First();
var email = firstItem as EmailMessage;
email.Load();
var propertySet = new PropertySet(BasePropertySet.FirstClassProperties, ItemSchema.MimeContent, EmailMessageSchema.IsRead);
service.LoadPropertiesForItems(new List<Item> { firstItem }, propertySet);
var body = firstItem.Body;
}
Doing email.Body or firstItem.Body retrives the same HTML.
This is an example of an email with encoded base64 image - see '& #43;' in img src:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<b>HIIIIIIIIIIIIIIIIIIIIIII <b><img src="data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOV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obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==">
</b></b>
</body>
</html>

How to click button and open window to send email in c#

I want to create a button so that user can click and it will open a small new window where they can send email. This window will have "From", "To", "Subject", "Content" fields and all of that will have default text, user can edit them (except for "From" field). See image below:
What I tried:
I created an email form by:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<p>
From:<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</p>
To:<asp:Literal ID="Literal2" runat="server"></asp:Literal>
<p>
Subject:<asp:Literal ID="Literal3" runat="server"></asp:Literal>
</p>
Content:<asp:Literal ID="Literal4" runat="server"></asp:Literal>
</form>
</body>
</html>
Then I try to link this form with my current code:
Current code: I can send email by this code:
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpclientaddresshere");
mail.From = new MailAddress("defaultFromEmail#domain.com");
mail.To.Add("email1#yahoo.com,email2#yahoo.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail";
SmtpServer.Credentials = new System.Net.NetworkCredential("mysmtpserver#something.com", "");
SmtpServer.Send(mail);
Now I don't know is this right to use the form above for email window purpose? And how could I format and link all the fields to my working code?
What I have done is like this:
public void SendEmail(string _from, string _fromDisplayName, string _to, string _toDisplayName, string _subject, string _body, string _password)
{
try
{
SmtpClient _smtp = new SmtpClient();
MailMessage _message = new MailMessage();
_message.From = new MailAddress(_from, _fromDisplayName); // Your email address and your full name
_message.To.Add(new MailAddress(_to, _toDisplayName)); // The recipient email address and the recipient full name // Cannot be edited
_message.Subject = _subject; // The subject of the email
_message.Body = _body; // The body of the email
_smtp.Port = 587; // Google mail port
_smtp.Host = "smtp.gmail.com"; // Google mail address
_smtp.EnableSsl = true;
_smtp.UseDefaultCredentials = false;
_smtp.Credentials = new NetworkCredential(_from, _password); // Login the gmail using your email address and password
_smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtp.Send(_message);
ShowMessageBox("Your message has been successfully sent.", "Success", 2);
}
catch (Exception ex)
{
ShowMessageBox("Message : " + ex.Message + "\n\nEither your e-mail or password incorrect. (Are you using Gmail account?)", "Error", 1);
}
}
And I am using it like this:
SendEmail(textBox2.Text, textBox5.Text, textBox3.Text, "YOUR_FULL_NAME", textBox4.Text, textBox6.Text, "YOUR_EMAIL_PASSWORD");
Here is the image:
(Although I am using WinForms and not Windows Presentation Forms).
May this answer would help you.
Cheers!

Mandrill Template is sent correctly once every 28 times

When I run the code below the Mandrill Template is sent correctly once every 28 times. Every other time it will send "Test_email". Does anyone know why this is? Can this be a trial version?
html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Table
<table style="text-align: center; border-spacing:5px; margin-left: auto;margin-right: auto;vertical-align: middle;width: 600px;background-color:lightgrey; padding-top:15px; padding-bottom:15px; padding-left:10px;padding-right:10px;border-radius:15px;">
<tr>
<td>Some Text here</td>
</tr>
</table>
</body>
</html>
C#
namespace Messages
{
class Program
{
static void Main(string[] args)
{
var fromAddress = new MailAddress("me#mail.com", "b");
var toAddress = new MailAddress("ano#gmail.com", "To Name");
const string fromPassword = "API Key";
const string subject = "test template email";
//const string body = "Test-email";
TemplateContent tp = new TemplateContent();
tp.name = "Test_email";
var smtp = new SmtpClient
{
Host = "smtp.mandrillapp.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = tp.name
})
{
smtp.Send(message);
}
}
}
}
If they're showing in the Outbound Activity, then your code was fine and Mandrill processed the mail. Is the issue that it shows as delivered in Mandrill but you don't see it? Or that it doesn't look like the template was applied? If you're sending to Gmail, you might see the content hidden because of the emails being included in a conversation. Look for three dots to expand the information. If they all have the same subject line and content, then Gmail will hide previously-received content as part of the conversations feature. If that's not the issue, then you should clarify exactly where you're seeing an issue in the process.

Categories

Resources