Sending mail via Java API: How to send the mail even if attachment fails? -
this code:
try { mimemessage message = new mimemessage(session); message.setfrom(new internetaddress(from)); message.addrecipient(message.recipienttype.to, new internetaddress(to)); message.setsubject(messagesubject); message.settext(messagebody); bodypart messagebodypart1 = new mimebodypart(); messagebodypart1.settext(messagebody); mimebodypart messagebodypart2 = new mimebodypart(); string filename = attachment; datasource source = new filedatasource(filename); messagebodypart2.setdatahandler(new datahandler(source)); messagebodypart2.setfilename(filename); multipart multipart = new mimemultipart(); multipart.addbodypart(messagebodypart1); multipart.addbodypart(messagebodypart2); message.setcontent(multipart ); transport.send(message); } catch (messagingexception mex) { mex.printstacktrace(); }
how can still send email if mail attachment fails reason? atm if attachment fails, email not sent, bad in case. should use try/catch statement , should have well? im new java (3-4 weeks)
edit: changed code this, didnt work
try { mimemessage message = new mimemessage(session); message.setfrom(new internetaddress(from)); message.addrecipient(message.recipienttype.to, new internetaddress(to)); message.setsubject(messagesubject); message.settext(messagebody); try { bodypart messagebodypart1 = new mimebodypart(); messagebodypart1.settext(messagebody); mimebodypart messagebodypart2 = new mimebodypart(); string filename = attachment; datasource source = new filedatasource(filename); messagebodypart2.setdatahandler(new datahandler(source)); messagebodypart2.setfilename(filename); multipart multipart = new mimemultipart(); multipart.addbodypart(messagebodypart1); multipart.addbodypart(messagebodypart2); message.setcontent(multipart); } catch (exception e) { message.settext(messagebody2); e.printstacktrace(); } transport.send(message); } catch (messagingexception mex) { mex.printstacktrace(); }
yes. expect able (pseudo-code follows)
try { // set standard message try { // perform attachment } catch { // perhaps amend original message indicate attachment failed } send(); } catch { // handle complete failure here... }
although i'd concentrate on why attachment fails. make sense ?
you may take approach of building/sending in 2 different methods, such don't have clean / modify message in face of failure. may cleaner approach e.g. (pseudo-code again)
try { sendmessagewithattachment(); } catch { sendmessagewithoutattachment(); }
Comments
Post a Comment