I am using something like the following to save a copy of the sent message in the user Sent folder in JavaMail. It works fine for emails with no attachment and for emails whose attachments are less than 1MB. But program stops before the code is actually executed for attachments greater than 1MB. Any idea how to deal with this one?
String host = ReadConfigPropertiesFile.getPropertyValue("server.host");
String smtpHost = ReadConfigPropertiesFile.getPropertyValue("smtp.host");
String from = "test#myserver.net";
String to = "test#myserver.net";
// Get system properties
Properties properties = System.getProperties();
// Setup smtp mail server
properties.setProperty(smtpHost, host);
properties.setProperty("mail.mime.encodeparameters", "true");
// properties.setProperty("mail.mime.decodeparameters","true");
properties.setProperty("mail.mime.encodefilename", "true");
// properties.setProperty("mail.mime.decodefilename","true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Peace ", "UTF-8");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message body
messageBodyPart.setContent("Hello attachment", "text/html; charset=UTF-8");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
String[] filename = {"C:/Users/Dake/Desktop/music.mp3"};
for (int i = 0; i < filename.length; i++) {
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename[i]);
messageBodyPart.setDataHandler(new DataHandler(source));
// messageBodyPart.setFileName(filename[i]);
//messageBodyPart.setHeader("Content-Type", "text/plain; charset=UTF-8; name="+MimeUtility.encodeText(filename[i]));
// messageBodyPart.setHeader("Content-ID", filename[i]);
messageBodyPart.setFileName(MimeUtility.encodeText(filename[i], "UTF-8", null)); //encode filename
//bodyPart.setFileName(MimeUtility.encodeText(attachment.getName(), "UTF-8", null));
multipart.addBodyPart(messageBodyPart);
}
// Put parts in message
message.setContent(multipart);
//set the time
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:MM:SS");
Date date = new Date();
String sentDate = df.format(date);
Date dd = (Date) df.parse(sentDate);
message.setSentDate(date);
// Send the message
Transport.send(message);
System.out.println("Message sent...");
// Copy message to "Sent Items" folder as read
Store store = session.getStore("imap");
store.connect(host, "user", "userpwd");
Folder folder = (Folder) store.getFolder("Sent");
if (!folder.exists()) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
System.out.println("appending...");
// folder.appendMessages(new Message[]{message});
try {
folder.appendMessages(new Message[]{message});
// Message[] msgs = folder.getMessages();
message.setFlag(FLAGS.Flag.RECENT, true);
} catch (Exception ignore) {
System.out.println("error processing message " + ignore.getMessage());
} finally {
store.close();
// folder.close(false);
}
System.out.println("Msg send and saved ....");
}
When I run the above code, it displays the appending.... and it stops there forever. And I am using Apache James server 3.0-beta4 as the mail server.
Is your server breaking the connection because it's taking too long to send the message to be appended? (If so, how long is it taking?)
Or is the server breaking the connection because it won't allow you to append a message that large?
Do you get any useful information from the server in the debug output?
I know this is a old question, but maybe this helps you or some others.
I guess the problem of your code is that you try to manipulate the Recent-Flag: message.setFlag(FLAGS.Flag.RECENT, true);. According to the IMAP-Standard the Recent-Flag can't be altered by clients.
Related
I am trying to implement a deferred sending function to my site which currently sends email via Microsoft Graph. I have found some articles about SingleValueLegacyExtendedProperty being used to defer sending, but so far has been unsuccessful with it.
My current code just ignores the deferred sending time and sends the email immediately.
var message = new Message
{
Subject = Subject,
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = bodyText
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = recipient
}
}
},
};
message.SingleValueExtendedProperties = new MessageSingleValueExtendedPropertiesCollectionPage
{
new SingleValueLegacyExtendedProperty()
{
Id = "SystemTime 0x3FEF",
Value = DateTimeToSend.ToString("o")
}
};
var saveToSentItems = true;
await graphServiceClient.Me
.SendMail(message, saveToSentItems)
.Request()
.PostAsync();
In this article they suggest that the ID should be String {8ECCC264-6880-4EBE-992F-8888D2EEAA1D} Name pidTagDeferredSendTime when passing as JSON but it looks like that was not successful for other. I checked and can confirm that it did not work for me either.
Its important that the DateTime that you want the message to be sent is in UTC eg
"value": "2022-08-01T23:39:00Z"
Using local time won't work as Exchange does everything in UTC
I have a RestSharp Client and Nancy Self Host Server.
What I want is
To send multipart form data from client and parse that data easily
from server :
Send binary file and Json data As Multipart Form Data from RestSharp client
and able to get binary file and Json object from Nancy Server
At Client using Restsharp : [ http://restsharp.org/ ] I try to send "multipart/form-data" requests which contains a binary file plus some meta data in json format:
var client = new RestClient();
...
IRestRequest restRequest = new RestRequest("AcmeUrl", Method.POST);
restRequest.AlwaysMultipartFormData = true;
restRequest.RequestFormat = DataFormat.Json;
// I just add File To Request
restRequest.AddFile("AudioData", File.ReadAllBytes("filePath"), "AudioData");
// Then Add Json Object
MyObject myObject = new MyObject();
myObject.Attribute ="SomeAttribute";
....
restRequest.AddBody(myObject);
client.Execute<MyResponse>(request);
At Server using Nancy[ http://nancyfx.org/ ], Itry to get File and Json Object [Meta Data ]
// Try To Get File : It Works
var file = Request.Files.FirstOrDefault();
// Try To Get Sended Meta Data Object : Not Works.
// Can Not Get MyObject Data
MyObject myObject = this.Bind<MyObject>();
For multipart data, Nancy's code is a bit more complex.
Try something like this:
Post["/"] = parameters =>
{
try
{
var contentTypeRegex = new Regex("^multipart/form-data;\\s*boundary=(.*)$", RegexOptions.IgnoreCase);
System.IO.Stream bodyStream = null;
if (contentTypeRegex.IsMatch(this.Request.Headers.ContentType))
{
var boundary = contentTypeRegex.Match(this.Request.Headers.ContentType).Groups[1].Value;
var multipart = new HttpMultipart(this.Request.Body, boundary);
bodyStream = multipart.GetBoundaries().First(b => b.ContentType.Equals("application/json")).Value;
}
else
{
// Regular model binding goes here.
bodyStream = this.Request.Body;
}
var jsonBody = new System.IO.StreamReader(bodyStream).ReadToEnd();
Console.WriteLine("Got request!");
Console.WriteLine("Body: {0}", jsonBody);
this.Request.Files.ToList().ForEach(f => Console.WriteLine("File: {0} {1}", f.Name, f.ContentType));
return HttpStatusCode.OK;
}
catch (Exception ex)
{
Console.WriteLine("Error!!!!!! {0}", ex.Message);
return HttpStatusCode.InternalServerError;
}
};
Have a look at:
http://www.applandeo.com/en/net-and-nancy-parsing-multipartform-data-requests/
I am displaying a page that contains some text and one image. I want to email the URL of this page to some friends. How to do this?
Check This -
Store store = Session.getDefaultInstance().getStore();
Folder[] folder = store.list(Folder.SENT);
Folder sent = folder[0];
Message msg = new Message(sent);
Address receipent[] = new Address[1];
try
{
receipent[0] = new Address(To_Address, name);
msg.addRecipients(Message.RecipientType.TO, receipent);
msg.setSubject("Test Mail");
msg.setContent("This mail is to remind you that programmatically we can send the mail");
msg.setPriority(Priority.HIGH);
Transport.send(msg);
}
catch (Exception e)
{
e.printStackTrace();
}
I make a post request of base64 encoded data to the receipt verification address as follows (this is in C#):
var postSerializer = new JavaScriptSerializer();
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(Receipt);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
var temp = new Dictionary<string, string>();
temp.Add("receipt-data", returnValue);
string jsonReceipt = postSerializer.Serialize(temp);
request.Method = "POST";
request.ContentType = "application/json";
byte[] postBytes = System.Text.Encoding.ASCII.GetBytes(jsonReceipt);
request.ContentLength = postBytes.Length;
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(postBytes, 0, postBytes.Length);
// Close the Stream object.
dataStream.Close();
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
I'm pretty sure things are in the right format because I'm not getting any exceptions back
from the apple receipt verification endpoint. The entirety of the response I get back is
{status : -42352}
And I can't find out what this error means anywhere. Does anyone know what this means or if there's an error in my code?
Just solved the same problem. Got the solution from here: Verify receipt for in App purchase
The problem was in post encoding. When I encoded post on my server using
$receipt = json_encode(array("receipt-data" => base64_encode($receiptdata)));
I had the same -42352 status. When I used my own function for encoding on iPhone - everything worked! Magic...
I am trying to send an email(in c#) from worker role(Azure) with an attachment(from blob storage).
I am able to send an email but attachment(word document) is blank.
The following function is called from worker role.
public void sendMail(string blobName)
{
InitStorage();//Initialize the storage
var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
container = blobStorage.GetContainerReference("Container Name");
CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
if (File.Exists("demo.doc"))
File.Delete("demo.doc");
FileStream fs = new FileStream("demo.doc", FileMode.OpenOrCreate);
blob.DownloadToStream(fs);
Attachment attach = new Attachment(fs,"Report.doc");
System.Net.Mail.MailMessage Email = new System.Net.Mail.MailMessage("User#hotmail.com", "User#gmail.com");
Email.Subject = "Text fax send via email";
Email.Subject = "Subject Of email";
Email.Attachments.Add(attach);
Email.Body = "Body of email";
System.Net.Mail.SmtpClient client = new SmtpClient("smtp.live.com", 25);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("User#hotmail.com", Password);
client.Send(Email);
fs.Flush();
fs.Close();
Email.Dispose();
}
Please tell me where I am doing wrong?
I would try do fs.Position = 0; before attaching creating your Attachement object.
What's probably happening is that it's trying to read from current position in the stream and that stream is at the end, so it reads nothing.
Just a guess, but you should probably be calling fs.Close() before sending the email.