Mail from Java

Sometimes you gotta send mail from outside an app server, in which case, this will get you started:

Sending Mail with the JavaMail API

You will need the JavaMail library (mail.jar) as well as the Java Activation Framework (activation.jar) to get it running…

	public MailSender() {
	    Properties props = new Properties();
	    props.put("mail.smtp.host", "mail.yourhostnamehere.com");
	    session = Session.getDefaultInstance(props, null);
	}
	
	public boolean sendEmail( String to, String from, String subject, String body ) {
		try {
			Message message = new MimeMessage( session );
			message.setFrom( new InternetAddress( from ) );
			message.addRecipient( RecipientType.TO, new InternetAddress( to ) );
			message.setSubject( subject );
			message.setText( body );
			
			Transport.send( message );
			return true;
		} catch( AddressException e ) {
			log.error( "ERROR Occurred:", e );
			e.printStackTrace();
		} catch( MessagingException e ) {
			log.error( "ERROR Occurred:", e );
			e.printStackTrace();
		}
		return false;
	}