Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public boolean sendEMail( String sender,EmailArtifact artifact) throws InvalidEmailAddressException, SendEmailException
- {
- try {
- javax.mail.Session session =null;
- if(StringUtils.isBlank(username)){
- session = Session.getInstance(props, null);
- }else{
- /**
- * Using Default session generates an error : access to Default Session denied~
- * It seems the appserver already created a session using Session.getDefaultSession
- * which is denying us access to it
- */
- session= javax.mail.Session.getInstance( props,
- new Authenticator ( ) {
- public PasswordAuthentication getPasswordAuthentication ( ) {
- return new PasswordAuthentication ( username, password ) ;
- }
- } );
- }
- MimeMessage message = new MimeMessage( session );
- message.setFrom(new InternetAddress( sender ));
- message.setHeader("Content-Type","text/plain; charset=\"UTF-8\"");
- message.setHeader("Content-Transfer-Encoding", "quoted-printable");
- if (artifact.getTo() != null) {
- for ( Iterator<String> it = artifact.getTo().iterator() ; it.hasNext() ; )
- message.addRecipient(
- javax.mail.Message.RecipientType.TO,
- new InternetAddress( (String) it.next() )
- );
- }
- if (artifact.getCc() != null) {
- for ( Iterator<String> it = artifact.getCc().iterator() ; it.hasNext() ; )
- message.addRecipient(
- javax.mail.Message.RecipientType.CC,
- new InternetAddress( (String) it.next() )
- );
- }
- if (artifact.getBcc() != null) {
- for ( Iterator<String> it = artifact.getBcc().iterator() ; it.hasNext() ; )
- message.addRecipient(
- javax.mail.Message.RecipientType.BCC,
- new InternetAddress( (String) it.next() )
- );
- }
- message.setSubject( artifact.getSubject() ,"UTF-8");
- message.setSentDate ( new Date()) ;
- // create and fill the first message part
- MimeBodyPart mbp1 = new MimeBodyPart ( ) ;
- mbp1.setContent(artifact.getBody() +"\n\n"+artifact.getSignature(), "text/plain; charset=UTF-8");
- mbp1.setHeader("Content-Type","text/plain; charset=UTF-8");
- mbp1.setHeader("Content-Transfer-Encoding", "quoted-printable");
- Multipart mp = new MimeMultipart ( ) ;
- mp.addBodyPart ( mbp1 ) ;
- for (Entry<String, byte[]> att : artifact.getAttachments().entrySet()) {
- MimeBodyPart attachment = new MimeBodyPart ( ) ;
- attachment.setDataHandler ( new DataHandler ( new ByteArrayDataSource(att.getValue(),"application/octet-stream") ) );
- attachment.setFileName(att.getKey());
- mp.addBodyPart ( attachment ) ;
- }
- // add the Multipart to the message
- message.setContent ( mp) ;
- Transport.send( message );
- return true;
- }
- catch ( AddressException e )
- {
- throw new InvalidEmailAddressException(e.getMessage());
- }
- catch ( MessagingException e )
- {
- throw new SendEmailException(e);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement