I use the JavaMail Spring implementation with Velocity template engine. Everything goes well when I send the mails, the pictures are displayed normally and the styles also apply.
The problem that I encounter is that at the reception the email client displays my email as containing attachments, which are actually the images that appear in my email.
I do not understand why the images sent with the mail are seen as pieces joined by the mail client. Somebody can help me please?
This is my code :
final MimeMessage message = mailSender.createMimeMessage();
final MimeMessageHelper helper = new MimeMessageHelper(message,true, "UTF-8");
try {
helper.setFrom(getSystemAddress());
if (replyTo != null) {
helper.setReplyTo(replyTo);
}
helper.setTo(to);
helper.setSubject(subject);
helper.setText(body, isHTML);
System.out.println("Helper message factory: "+helper);
FileSystemResource res = new FileSystemResource(new File(MailHandler.class.getResource("logo-email.png").getFile()));
FileSystemResource res1 = new FileSystemResource(new File(MailHandler.class.getResource("bg-header.PNG").getFile()));
helper.addInline("cid2", res1);
helper.addInline("cid1", res);
mailSender.send(message);
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'm using a web server to control devices in the house with a microcontroller running .netMF (netduino plus 2). The code below writes a simple html page to a device that connects to the microcontroller over the internet.
while (true)
{
Socket clientSocket = listenerSocket.Accept();
bool dataReady = clientSocket.Poll(5000000, SelectMode.SelectRead);
if (dataReady && clientSocket.Available > 0)
{
byte[] buffer = new byte[clientSocket.Available];
int bytesRead = clientSocket.Receive(buffer);
string request =
new string(System.Text.Encoding.UTF8.GetChars(buffer));
if (request.IndexOf("ON") >= 0)
{
outD7.Write(true);
}
else if (request.IndexOf("OFF") >= 0)
{
outD7.Write(false);
}
string statusText = "Light is " + (outD7.Read() ? "ON" : "OFF") + ".";
string response = WebPage.startHTML(statusText, ip);
clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(response));
}
clientSocket.Close();
}
public static string startHTML(string ledStatus, string ip)
{
string code = "<html><head><title>Netduino Home Automation</title></head><body> <div class=\"status\"><p>" + ledStatus + " </p></div> <div class=\"switch\"><p>On</p><p>Off</p></div></body></html>";
return code;
}
This works great, so I wrote a full jquery mobile website to use instead of the simple html. This website is stored on the SD card of the device and using the code below, should write the full website in place of the simple html above.
However, my problem is the netduino only writes the single HTML page to the browser, with none of the JS/CSS style files that are referenced in the HTML. How can I make sure the browser reads all of these files, as a full website?
The code I wrote to read the website from the SD is:
private static string getWebsite()
{
try
{
using (StreamReader reader = new StreamReader(#"\SD\index.html"))
{
text = reader.ReadToEnd();
}
}
catch (Exception e)
{
throw new Exception("Failed to read " + e.Message);
}
return text;
}
I replaced string code = " etc bit with
string code = getWebsite();
How can I make sure the browser reads all of these files, as a full website?
Isn't it already? Use an HTTP debugging tool like Fiddler. As I read from your code, your listenerSocket is supposed to listen on port 80. Your browser will first retrieve the results of the getWebsite call and parse the HTML.
Then it'll fire more requests, as it finds CSS and JS references in your HTML (none shown). These requests will, as far as we can see from your code, again receive the results of the getWebsite call.
You'll need to parse the incoming HTTP request to see what resource is being requested. It'll become a lot easier if the .NET implementation you run supports the HttpListener class (and it seems to).
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)
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);