how to send mail with image attachment in blackberry - blackberry

I am developing a BlackBerry application that uses the Mail functionality. My problem is
I want to send mail with an image attachment. How can I do that?

You can convert the image to byte array and then use the following method to send the file as attachment.
public synchronized boolean sendMail(final byte []data)
{
Folder[] folders = store.list(4);
Folder sentfolder = folders[0];
// create a new message and store it in the sent folder
msg = new Message(sentfolder);
multipart = new Multipart();
textPart = new TextBodyPart(multipart,"Image");
Address recipients[] = new Address[1];
try {
recipients[0] = new Address(address, "XYZ");
msg.addRecipients(Message.RecipientType.TO, recipients);
msg.setSubject("Image");
try {
Thread thread = new Thread("Send mail") {
public void run() {
try {
attach = new SupportedAttachmentPart(
multipart, "application/octet-stream",
"title",data);
multipart.addBodyPart(textPart);
multipart.addBodyPart(attach);
msg.setContent(multipart);
Transport.send(msg);
}
catch(SendFailedException e)
{
}
catch (final MessagingException e) {
}
catch (final Exception e) {
}
}
};
thread.start();
return true;
}
catch (final Exception e)
{
}
}catch (final Exception e) {
}
return false;
}

This may be help you check it
//create a multipart
Multipart mp = new Multipart();
//data for the content of the file
String fileData = "<html>just a simple test</html>";
String messageData = "Mail Attachment Demo";
//create the file
SupportedAttachmentPart sap = new SupportedAttachmentPart(mp,"text/html","file.html",fileData.getBytes());
TextBodyPart tbp = new TextBodyPart(mp,messageData);
//add the file to the multipart
mp.addBodyPart(tbp);
mp.addBodyPart(sap);
//create a message in the sent items folder
Folder folders[] = Session.getDefaultInstance().getStore().list(Folder.SENT);
Message message = new Message(folders[0]);
//add recipients to the message and send
try {
Address toAdd = new Address("email#company.com","my email");
Address toAdds[] = new Address[1];
toAdds[0] = toAdd;
message.addRecipients(Message.RecipientType.TO,toAdds);
message.setContent(mp);
Transport.send(message);
} catch (Exception e) {
Dialog.inform(e.toString());
}
this is for Image file
InputStream inputStream;
FileConnection fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
if(fconn.exists()){
inputStream=fconn.openInputStream();
byte[] data = IOUtilities.streamToBytes(inputStream);
inputStream.close();
fconn.close();
Multipart multipart = new Multipart();
SupportedAttachmentPart attach = new SupportedAttachmentPart(multipart, ".txt/.jpeg", "attachment1", data);
multipart.addBodyPart(attach);
}

Related

JavaMail MIME attachment link by cid

Background
I have banged my head against this for a while and not made much progress. I am generating MPEG_4 / AAC files in Android and sending them by email as .mp3 files. I know they aren't actually .mp3 files, but that allows Hotmail and Gmail to play them in Preview. They don't work on iPhone though, unless they are sent as .m4a files instead which breaks the Outlook / Gmail Preview.
So I have thought of a different approach which is to attach as a .mp3 file but have an HTML link in the email body which allows the attached file to be downloaded and specifies a .m4a file name. Gmail / Outlook users can click the attachment directly whereas iPhone users can use the HTML link.
Issue
I can send an email using JavaMail with HTML in it including a link which should be pointing at the attached file to allow download of that file by the link. Clicking on the link in Gmail (Chrome on PC) gives a 404 page and iPhone just ignores my clicking on the link.
Below is the code in which I generate a multipart message and assign a CID to the attachment which I then try to access using the link in the html part. It feels like I am close, but maybe that is an illusion. I'd be massively grateful if someone could help me fix it or save me the pain if it isn't possible.
private int send_email_temp(){
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtp_host_setting);
//props.put("mail.debug", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", smtp_port_setting);
session = Session.getInstance(props);
ActuallySendAsync_temp asy = new ActuallySendAsync_temp(true);
asy.execute();
return 0;
}
class ActuallySendAsync_temp extends AsyncTask<String, String, Void> {
public ActuallySendAsync_temp(boolean boo) {
// something to do before sending email
}
#Override
protected Void doInBackground(String... params) {
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(recipient_email_address));
message.setSubject(email_subject);
Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
String file = mFileName;
/**/
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
/* /
File ff = new File(file);
try {
messageBodyPart.attachFile(ff);
} catch(IOException eio) {
Log.e("Message Error", "Old Macdonald");
}
/* /
messageBodyPart = new PreencodedMimeBodyPart("base64");
byte[] file_bytes = null;
File ff = new File(file);
try {
int length = (int) ff.length();
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(ff));
file_bytes = new byte[length];
reader.read(file_bytes, 0, length);
reader.close();
} catch (IOException eio) {
Log.e("Message Error", "Old Macdonald");
}
messageBodyPart.setText(Base64.encodeToString(file_bytes, Base64.DEFAULT));
messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
/**/
messageBodyPart.setFileName( DEFAULT_AUDIO_FILENAME );//"AudioClip.mp3");
//messageBodyPart.setContentID("<audio_clip>");
String content_id = UUID.randomUUID().toString();
messageBodyPart.setContentID("<" + content_id + ">");
messageBodyPart.setDisposition(Part.ATTACHMENT);//INLINE);
messageBodyPart.setHeader("Content-Type", "audio/mp4");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart messageBodyText = new MimeBodyPart();
//final String MY_HTML_MESSAGE = "<h1>My HTML</h1><a download=\"AudioClip.m4a\" href=\"cid:audio_clip\">iPhone Download</a>";
final String MY_HTML_MESSAGE = "<h1>My HTML</h1><a download=\"AudioClip.m4a\" href=\"cid:" + content_id + "\">iPhone Download</a>";
messageBodyText.setContent( MY_HTML_MESSAGE, "text/html");
multipart.addBodyPart(messageBodyText);
message.setContent(multipart);
Print_Message_To_Console(message);
Transport transport = session.getTransport("smtp");
transport.connect(smtp_host_setting, username, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
e.printStackTrace();
} finally {
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
// something to do after sending email
}
}
int Print_Message_To_Console(Message msg) {
int ret_val = 0;
int line_num = 0;
InputStream in = null;
InputStreamReader inputStreamReader = null;
BufferedReader buff_reader = null;
try {
in = msg.getInputStream();
inputStreamReader = new InputStreamReader(in);
buff_reader = new BufferedReader(inputStreamReader);
String temp = "";
while ((temp = buff_reader.readLine()) != null) {
Log.d("Message Line " + Integer.toString(line_num++), temp);
}
} catch(Exception e) {
Log.d("Message Lines", "------------ OOPS! ------------");
ret_val = 1;
} finally {
try {
if (buff_reader != null) buff_reader.close();
if (inputStreamReader != null) inputStreamReader.close();
if (in != null) in.close();
} catch(Exception e2) {
Log.d("Message Lines", "----------- OOPS! 2 -----------");
ret_val = 2;
}
}
return ret_val;
}
You need to create a multipart/related and set the main text part as the first body part.

The UWP application use too many memory when I use Stream

I create a app to read ZipArchive(100+ photo),And Use Stream, MemoryStream, IRandomAccessStream, and BinaryReader to setSource of the bitmapImage.
private byte[] GetBytes(ZipArchiveEntry entity)
{
Stream stream = entity.Open();
MemoryStream ms = new MemoryStream();
BinaryReader reader = null;
byte[] imageData = null;
try
{
stream.CopyTo(ms);
imageData = new byte[ms.Length];
string fileclass = "";
reader = new BinaryReader(ms);
ms.Seek(0, 0);
imageData = reader.ReadBytes((int)ms.Length);
//Verify png jpg bmp
some code and return imageData
//throw exception,return null
else
{
throw new Exception();
}
}
catch (Exception ex)
{
return null;
}
//Dispose
}
BitmapImage.SetSource by byte[]
public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
{
MangaPageEntity mpe = new MangaPageEntity();
mpe.Index = index;
IRandomAccessStream iras = null;
try
{
byte[] data = GetBytes(entity);
iras = data.AsBuffer().AsStream().AsRandomAccessStream();
iras.Seek(0);
await mpe.Picture.SetSourceAsync(iras);
}//catch and dispose
return mpe;
In this way, It use too many memory too run at phone ..
Try to put your streams and other IDisposable into using statement:
private byte[] GetBytes(ZipArchiveEntry entity)
{
using (Stream stream = entity.Open())
using (MemoryStream ms = new MemoryStream())
{
byte[] imageData = null;
try
{
stream.CopyTo(ms);
imageData = new byte[ms.Length];
string fileclass = "";
using (BinaryReader reader = new BinaryReader(ms))
{
ms.Seek(0, 0);
imageData = reader.ReadBytes((int)ms.Length);
}
//Verify png jpg bmp some code and return imageData
//throw exception,return null
else
{
throw new Exception();
}
}
catch (Exception ex)
{
return null;
}
}
//Dispose
}
public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
{
MangaPageEntity mpe = new MangaPageEntity();
mpe.Index = index;
try
{
byte[] data = GetBytes(entity);
using (IRandomAccessStream iras = data.AsBuffer().AsStream().AsRandomAccessStream())
{
iras.Seek(0);
await mpe.Picture.SetSourceAsync(iras);
}
}//catch and dispose
return mpe;
}
When your code leaves using it calls Dispose(). Some more to read: Uses of “using” in C#, What is the C# Using block and why should I use it? and probably some more.

How to send HttpPostedFileBase to S3 via AWS SDK

I'm having some trouble getting uploaded files to save to S3. My first attempt was:
Result SaveFile(System.Web.HttpPostedFileBase file, string path)
{
//Keys are in web.config
var t = new Amazon.S3.Transfer.TransferUtility(Amazon.RegionEndpoint.USWest2);
try
{
t.Upload(new Amazon.S3.Transfer.TransferUtilityUploadRequest
{
BucketName = Bucket,
InputStream = file.InputStream,
Key = path
});
}
catch (Exception ex)
{
return Result.FailResult(ex.Message);
}
return Result.SuccessResult();
}
This throws an exception with the message: "The request signature we calculated does not match the signature you provided. Check your key and signing method." I also tried copying file.InputStream to a MemoryStream, then uploading that, with the same error.
If I set the InputStream to:
new FileStream(#"c:\folder\file.txt", FileMode.Open)
then the file uploads fine. Do I really need to save the file to disk before uploading it?
This is my working version first the upload method:
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
request.WithBucketName(_bucketName)
.WithCannedACL(S3CannedACL.PublicRead)
.WithKey(filePath).InputStream = inputStream;
request.AddHeaders(AmazonS3Util.CreateHeaderEntry("ContentType", contentType));
_amazonS3Client.PutObject(request);
}
catch (Exception exception)
{
// log or throw;
return false;
}
return true;
}
I just get the stream from HttpPostedFileBase.InputStream
(Note, this is on an older version of the Api, the WithBucketName syntax is no longer supported, but just set the properties directly)
Following the comment of shenku, for newer versions of SDK.
public bool Upload(string filePath, Stream inputStream, double contentLength, string contentType)
{
try
{
var request = new PutObjectRequest();
string _bucketName = "";
request.BucketName = _bucketName;
request.CannedACL = S3CannedACL.PublicRead;
request.InputStream = inputStream;
request.Key = filePath;
request.Headers.ContentType = contentType;
PutObjectResponse response = _amazonS3Client.PutObject(request);
return true;
}catch(Exception ex)
{
return false;
}
}

I have following code to upload my attachment.But I couldn't upload it into my own path. How should I change following code?

if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
Iterator iterator = items.iterator();
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File path = new File(root+"/uploads");
if (!path.exists()) {
boolean status = path.mkdirs();
System.out.println("status"+status);
}
File uploadedFile = new File(path + "/" + fileName);
item.write(uploadedFile);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
My attachment are stored in machine dependent location. How I change it into my own location? (ex:-war/uploads/..). Now path shows my machine name also.(ex:-/home/name/NetBeansProjects/prjname/dist/wldeploy/prjname/prjname-war.war/uploads/image.jpg)

Sending PIN-message in BlackBerry does not work

My application sends PIN-messages, but when my application sends a PIN-message, it just arrives to outbox folder and remains there with clock icon. And it is not being sent really to the recipient.
Below there is my code, could you please tell me what is wrong with it:
public class SendPin implements carinfoResource
{
private static ResourceBundle _res =
ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);
public SendPin() {
}
public void sendPin(int command)
{
Store store = Session.getDefaultInstance().getStore();
//retrieve the sent folder
Folder[] folders = store.list(Folder.SENT);
Folder sentfolder = folders[0];
//create a new message and store it in the sent folder
Message msg = new Message(sentfolder);
PINAddress recipients[] = new PINAddress[1];
try{
//create a pin address with destination address of 20000000
recipients[0]= new PINAddress("289A2FF6", "Soporte Desarrollo");
}
catch (AddressException ae)
{
System.err.println(ae);
}
try{
//add the recipient list to the message
msg.addRecipients(Message.RecipientType.TO, recipients);
//Command travel without troubles
if(command == 0)
{
//set a subject for the message
msg.setSubject(_res.getString(OKSUBJECT));
//sets the body of the message
msg.setContent(_res.getString(OKBODY));
}
else
{
//set a subject for the message
msg.setSubject(_res.getString(ISSUESUBJECT));
//sets the body of the message
msg.setContent(_res.getString(ISSUEBODY)+" "+this.getIMSI());
}
Transport.send(msg);
}
catch (MessagingException me)
{
System.err.println(me);
}
}
public String getIMSI() {
String imsi = null;
try {
imsi = GPRSInfo.imeiToString(SIMCardInfo.getIMSI());
} catch (Exception e) {
System.err.println(e);
}
return imsi;
}
}

Resources