I have written a WebAPI controller method that finds a mail by its unique ID from ExchangeOnline. I wrote a small model class in order to store some attributes of a mail like the subject, the sender, the date received and so on.
Now I also want to access file attachments if the mail has such attachments. Therefore, I wrote this code (just the relevant part):
List<AttachmentItem> attDataContainer = new List<AttachmentItem>();
EmailMessage originalMail = EmailMessage.Bind(service, new ItemId(uniqueID), new PropertySet(ItemSchema.Attachments));
foreach (Attachment att in originalMail.Attachments)
{
if (att is FileAttachment && !att.IsInline)
{
FileAttachment fa = att as FileAttachment;
fa.Load();
attDataContainer.Add(
new AttachmentItem
{
ID = fa.Id,
Name = fa.Name,
ContentID = fa.ContentId,
ContentType = fa.ContentType,
ContentLocation = fa.ContentLocation,
Content = Convert.ToBase64String(fa.Content),
Size = fa.Size
});
}
}
The method indeed finds the attachments and displays all of the attributes you can see in the "AttachmentItem" object - BUT NOT the fa.Content attribute.
I have crwaled almost any document I could find on this (especially the *.Load() part as well as much examples. But in my case I get "byte[0]" when debugging the output.
Do you have any idea for me what could be the reason for this?
PS: By the way, I have version v2.0.50727 of Microsoft.Exchange.WebServices referenced.
Best regards and thanks in advance,
Marco
When you call the load method on the Attachment that should make a GetAttachment request to the server which will return the data for that Attachment. If you enable tracing https://msdn.microsoft.com/en-us/library/office/dn495632(v=exchg.150).aspx that should allow you to follow the underlying SOAP requests which should help with troubleshooting (eg you can see what the server is returning which is important).
The other thing to check is that is this is a real attachment vs a One Drive attachment which could be the case on ExchangeOnline.
I wrote a program that includes an embedded web browser that loads a website which have a changing part (the part changes about 2 times a week and it have no regular timing pattern) that I want to search for a particular part in the opened webpage source code after refreshing the webpage in a specified time interval.
I found many things similar to my question but this is what I want and those questions doesn't have:
search embedded webpage source (they searching the webpage without embedding, and I had to embed it because I had to login before I see the particular page)
so this is the procedure I'm trying to do:
1- open a website in embedded web browser
2- after user logged in, with a press of button in program, it hides the embedded
web browser and start to refresh the page in a time interval (like
every minute) and search if the particular code changed in the source of
that opened webpage
any other/better Ideas appreciated
thanks
Many years ago I wrote an app to reintegrate forum posts from several pages into one and I struggled with the login issue too and thought it was only possible using an embedded browser. As it turns out, it's possible to use System.Net in .NET to handle web pages that need a login as you can pull the cookies out and keep them on hand. I would suggest you do that and move away from the embedded browser.
Unfortunately I wrote the code in C# originally, but as it's .NET and is mostly classes-based, it shouldn't be too difficult to port over.
The Basic Principle
Find out what information is included in the POST when you login, which you can do in Chrome with developer mode on (F12). Convert that to a byteArray, POST it to the page, store the cookies and make another call with the cookie data later on. You will need a class variable to hold the cookies.
Code:
private void Login()
{
byte[] byteArray = Encoding.UTF8.GetBytes("username=" + username + "&password=" + password + "&autologin=on&login=Log+in"); // Found by investigation
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("yourURL");
request.AllowAutoRedirect = false;
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.Found)
{
// Well done, your login has been accepted
loginDone = true;
cookies = request.CookieContainer;
}
else
{
// If at first you don't succeed...
}
response.Close();
}
private string GetResponseHTML(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.AllowAutoRedirect = false;
// Add cookies from Login()
request.CookieContainer = cookies;
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
string sResponse = "";
StreamReader reader = null;
if (((HttpWebResponse)response).StatusCode == HttpStatusCode.OK)
{
reader = new StreamReader(response.GetResponseStream());
sResponse = reader.ReadToEnd();
reader.Close();
}
response.Close();
return sResponse;
}
Hope that helps.
I had to change to C# and I found what I was looking for:
string webPageSource = webBrowser1.DocumentText;
That gave me the source of web page opened in webBrowser1 control.
I'm working on project using MSMQ, messages are both sent and received.
However, when trying to access the message body I get an error noting "Root element is missing"
I can't see the problem, but wondered whether the Html in the message body could be causing it.
Can MSMQ deal with Html? What about Xml Serialisation with HTML in the body elements?
Thanks
Try using a BinaryMessageFormatter like this (and similarly on the receiving end):
using (MessageQueue queue = new MessageQueue(".\\Private$\\msmq1"))
{
queue.Formatter = new BinaryMessageFormatter();
using (Message message = new Message())
{
message.Body = "<html><body>my html here</body></html>;
message.Recoverable = true;
message.Formatter = new BinaryMessageFormatter();
message.TimeToBeReceived = TimeSpan.MaxValue;
queue.Send(message);
}
}
Or create a MsmqTransportObject with an Html String property and transfer that instead.
The XmlMessageFormatter makes no sense if both the send and receive ends are using .NET (in which case you can safely use BinaryMessageFormatter)
Currently I'm sending E-Mail messages by SPUtility.SendMail. I'd like to embed images into my message so i can give it a little bit style (div backgrounds, logo images etc.).
Is this possible?
P.S. I can't give direct URL addresses to image SRCs because the resources are located in a site which belongs to a private network which requires authentication for accessing to the files.
Edit:
I did some research before asking here, ofcourse the first thing i encountered was the System.Net.Mail (do you know that there is a whole web site devoted to it). But the Sharepoint Deployment team in my client's company has some strict rules about custom coding. They have coding guide lines and everything. I'm trying to stick with the SP SDK as hard as i can.
The most straighforward way for me has been through using System.Net.Mail, since you can inline your own content.
Here's a sample usage
using (MailMessage msg = new MailMessage("fromaddress", "toaddress"))
{
msg.Subject = "subject";
msg.Body = "content";
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp server name");
smtp.Send(msg);
}
Same concept applies to using SPUtility.SendMail (aside from the fact that you'll need a reference to your SPWeb:
From http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.utilities.sputility.sendemail.aspx
try
{
SPWeb thisWeb = SPControl.GetContextWeb(Context);
string toField = "someone#microsoft.com";
string subject = "Test Message";
string body = "Message sent from SharePoint";
bool success = SPUtility.SendEmail(thisWeb,true, false, toField, subject, body);
}
catch (Exception ex)
{
// handle exception
}
The second boolean parameter in SendMail is false to disable HTML encoding, so you can use your <img > and <div > tags in the message body.
I've been given the task of optimizing HTML emails for different email/webmail clients. I used to test the HTML file by doing a trick in Outlook Express, to make it send the raw HTML, but Microsoft seems to have stopped supplying Outlook Express now (I think "Live Mail" is supposed to replace it).
So my question is, is there a simple, quick way to send HTML emails? Maybe even a freeware program that does the job?
Puts Mail is the best bet these days. Check out an answer to a similar question by the creator of Puts Mail.
I would use python, here at the bottom is an example how to create a HTML email with a text default: http://docs.python.org/library/email-examples.html
you can parameterize this, encapsulate in functions, read content from files, etc. (make sure, that you set localhost in "s = smtplib.SMTP('localhost') " to your smtp server)
If you are just looking to test whether an HTML email displays properly in various clients, I would use sendmail.exe (windows only).
You can save a .html file and pipe it into that program on the command-line as the email content. There are command line options for from/to/subject/server, etc.
This would allow you to rapidly send and re-send emails by just editing the .html file and running the command-line again. No programming required.
Edit: there is a similar command-line tool for Linux with the same name.
I would not even go with any language ...
I would stop at MailChimp and set up a free account (max of 500 subscribers and 3000 sends per month) ... 3000 sends is enough to test right? :)
It has all the tools you need to send emails professionally (and maybe set up an account to your client/friend so they/he can use MailChimp in their Newsletters)
while you're at it, see their resources page as well the perfect tool to know what can we use in Newsletters using CampaignMonitor own Guide to CSS support in email clients
hope it helps
Ruby variant:
require "mail"
options = {
:address => "smtp.gmail.com",
:port => 587,
:domain => "smtp.gmail.com",
:user_name => "me#gmail.com",
:password => "password",
:enable_starttls_auto => true,
:authentication => :plain,
}
Mail.defaults do
delivery_method :smtp, options
end
mail = Mail.new do
to "me#gmail.com"
from "Me Me me#gmail.com"
subject "test email"
html_part do
content_type "text/html; charset=UTF-8"
body File.read("index.html")
end
end
mail.deliver
Do not forget to enable access from https://www.google.com/settings/security/lesssecureapps
I believe you can send html emails from Mozilla's Thunderbird email client.
http://www.mozillamessaging.com/en-US/thunderbird/
This is what I used to send test emails. Or I guess you could use your email provider too.
If you're on a Mac you can send HTML email super quickly using Safari and Mail. I blogged about the details at the link below, but basically you just view your HTML file in Safari and select File > Mail Contents of This Page.
http://www.ravelrumba.com/blog/send-html-email-with-safari-mail-for-fast-testing/
Very late to the conversation, but here is the quickest method (although far from best practice) to send a html email:
View your rendered html in a web browser (like a web page), then ctrl+a select the entire page then ctrl+c copy and ctrl+v paste that rendered html result into the body of your email. Doesn't get any easier than that...
Just note that your images need to be hosted if you want the recipient to see them.
If you are running .NET and you have a Gmail account this is one easy way
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.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 = body
})
{
smtp.Send(message);
}
see Sending email in .NET through Gmail for more details
A Test Mail Server Tool can help with that -if you just need to receive and view any emails sent by your application.
I send HTML email (often in bulk) using PHPMailer. It has worked great for me.
Also you can use PowerShell
A Windows-only free solution where you typically don't have to install anything special is to use ASP or WSH. I opt for JScript instead of VBScript:
function sendHtml(recipients, subject, html) {
var mail = Server.CreateObject("CDO.Message");
mail.From = "Tester <tester#example.com>";
mail.Subject = subject;
mail.To = recipients.join(";");
mail.HTMLBody = html;
// Do the following if you want to directly use a specific SMTP server
mail.Configuration.Fields.Item(
"http://schemas.microsoft.com/cdo/configuration/sendusing") = 2;
mail.Configuration.Fields.Item(
"http://schemas.microsoft.com/cdo/configuration/smtpserver")
= "smtp.example.com";
mail.Configuration.Fields.Item(
"http://schemas.microsoft.com/cdo/configuration/smtpserverport")
= 25;
mail.Configuration.Fields.Update();
mail.Send();
}
Note: However, your HTML may end up getting slightly reformatted with this approach.
function sendHtml(recipients, subject, html) {
var mail = Server.CreateObject("CDO.Message");
mail.From = "Tester <tester#example.com>";
mail.Subject = subject;
mail.To = recipients.join(";");
mail.HTMLBody = html;
// Do the following if you want to directly use a specific SMTP server
mail.Configuration.Fields.Item(
"http://schemas.microsoft.com/cdo/configuration/sendusing") = 2;
mail.Configuration.Fields.Item(
"http://schemas.microsoft.com/cdo/configuration/smtpserver")
= "smtp.example.com";
mail.Configuration.Fields.Item(
"http://schemas.microsoft.com/cdo/configuration/smtpserverport")
= 25;
mail.Configuration.Fields.Update();
mail.Send();
}
Maybe you can use System.Net.Mail in .NET?
You can read from an email template and assing to a MailMessage body.
To send email
System.Net.Mail.MailMessage msg = CreateMailMessage();
SmtpClient sc = new SmtpClient();
sc.Host = ConfigurationManager.AppSettings["SMTPServer"];
sc.Port = 0x19;
sc.UseDefaultCredentials = true;
sc.Send(msg);