package siprp.medicina.processo.mail;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MailSender
{
	protected String from = "marcacoes@siprp.pt";
	protected String mailServer = "mail2.evolute.pt";
	protected String userName = "auto@siprp.pt";
	protected String password = "sdfoyias78e";
	
	public MailSender()
	{
		
	}

	public void send( String to, String bcc, String subject, String body, String attachmentNames[], List<File> attachments ) throws Exception
	{
		Properties props = System.getProperties();
		props.put( "mail.smtp.host", mailServer );
	    props.put( "mail.smtp.auth", "true" );

	    Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getInstance( props, auth );
		
		MimeMessage msg = new MimeMessage( session );
		
		msg.setFrom( new InternetAddress( from ) );
		msg.setReplyTo( new Address[]{ new InternetAddress(from)} );
		msg.setRecipients( Message.RecipientType.TO, InternetAddress.parse( to, true ) );
		msg.setRecipients( Message.RecipientType.BCC, InternetAddress.parse( bcc, true ) );
		msg.setSubject( subject );
		
		MimeBodyPart bodyPart = new MimeBodyPart();
		bodyPart.setContent( body,"text/html" );
		
		Multipart multipart = new MimeMultipart();
		multipart.addBodyPart(bodyPart);
		
		if( attachmentNames != null && !attachments.isEmpty() )
		{
			for(int i = 0; i < attachmentNames.length; ++i )
			{
//				String attachName = attachmentNames[i];
				MimeBodyPart attachPart = new MimeBodyPart();
				DataSource dataSource = new FileDataSource(attachments.get(i));
				attachPart.setDataHandler( new DataHandler(dataSource));
				attachPart.setFileName(attachments.get(i).getName());
				multipart.addBodyPart(attachPart, i + 1);
			}
		}
		msg.setContent(multipart);
		msg.setHeader( "X-Mailer", "Evolute Mailer" );
		msg.setSentDate( new Date() );
		Transport.send( msg );
	}
	
	private class SMTPAuthenticator extends javax.mail.Authenticator
	{

	    public PasswordAuthentication getPasswordAuthentication()
	    {
	        return new PasswordAuthentication(userName, password);
	    }
	}
}
