javax.mail.Transport Java Examples

The following examples show how to use javax.mail.Transport. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SendMailJob.java    From AsuraFramework with Apache License 2.0 7 votes vote down vote up
/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 */
public void execute(JobExecutionContext context)
    throws JobExecutionException {

    JobDataMap data = context.getMergedJobDataMap();

    MailInfo mailInfo = populateMailInfo(data, createMailInfo());
    
    getLog().info("Sending message " + mailInfo);

    try {
        MimeMessage mimeMessage = prepareMimeMessage(mailInfo);
        
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new JobExecutionException("Unable to send mail: " + mailInfo,
                e, false);
    }

}
 
Example #2
Source File: EmailNotifierEngine.java    From repairnator with MIT License 7 votes vote down vote up
public void notify(String subject, String message) {
    if (this.from != null && !this.to.isEmpty()) {
        Message msg = new MimeMessage(this.session);

        try {
            Address[] recipients = this.to.toArray(new Address[this.to.size()]);
            Transport transport = this.session.getTransport();
            
            msg.setFrom(this.from);
            msg.addRecipients(Message.RecipientType.TO, recipients);
            msg.setSubject(subject);
            msg.setText(message);
            
            transport.connect();
            transport.sendMessage(msg, recipients);
            transport.close();
        } catch (MessagingException e) {
            logger.error("Error while sending notification message '" + subject + "'", e);
        }
    } else {
        logger.warn("From is null or to is empty. Notification won't be send.");
    }

}
 
Example #3
Source File: TestMailClient.java    From holdmail with Apache License 2.0 7 votes vote down vote up
public void sendEmail(String fromEmail, String toEmail, String subject, String textBody, String htmlBody) {
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(subject);

        // Set the message
        createMultiMimePart(message, textBody, htmlBody);

        Transport.send(message);
    }
    catch (MessagingException e) {
        throw new HoldMailException("Failed to send email : " + e.getMessage(), e);
    }
}
 
Example #4
Source File: MailSender.java    From openwebflow with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void sendMail(String receiver, String subject, String message) throws Exception
{
	Properties properties = new Properties();
	properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议
	properties.setProperty("mail.smtp.auth", "true");//需要验证

	Session session = Session.getInstance(properties);
	session.setDebug(false);
	//邮件信息
	Message messgae = new MimeMessage(session);
	messgae.setFrom(new InternetAddress(getMailFrom()));//设置发送人
	messgae.setText(message);//设置邮件内容
	messgae.setSubject(subject);//设置邮件主题
	//发送邮件
	Transport tran = session.getTransport();
	tran.connect(getServerHost(), getServerPort(), getAuthUserName(), getAuthPassword());
	tran.sendMessage(messgae, new Address[] { new InternetAddress(receiver) });//设置邮件接收人
	tran.close();

	Logger.getLogger(this.getClass()).debug(String.format("sent mail to <%s>: %s", receiver, subject));
}
 
Example #5
Source File: SmtpEmailSender.java    From microservices-testing-examples with MIT License 6 votes vote down vote up
public void send(String email) throws SmtpEmailSenderException {
  try {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(FROM));
    message.addRecipient(TO, new InternetAddress(email));
    message.setSubject("Welcome!");
    message.setText("It's our pleasure to have you as a member :)");
    Transport.send(message);
  } catch (MessagingException e) {
    throw new SmtpEmailSenderException(e);
  }
}
 
Example #6
Source File: MailSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
private void putOnTransport(Session session, Message msg) throws SenderException {
	// connect to the transport
	Transport transport = null;
	try {
		transport = session.getTransport("smtp");
		transport.connect(getSmtpHost(), getCredentialFactory().getUsername(), getCredentialFactory().getPassword());
		if (log.isDebugEnabled()) {
			log.debug("MailSender [" + getName() + "] connected transport to URL [" + transport.getURLName() + "]");
		}
		transport.sendMessage(msg, msg.getAllRecipients());
	} catch (Exception e) {
		throw new SenderException("MailSender [" + getName() + "] cannot connect send message to smtpHost [" + getSmtpHost() + "]", e);
	} finally {
		if (transport != null) {
			try {
				transport.close();
			} catch (MessagingException e1) {
				log.warn("MailSender [" + getName() + "] got exception closing connection", e1);
			}
		}
	}
}
 
Example #7
Source File: GMailClient.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void sendHtmlWithAttachment(String to, String subj, String body,
                                   QrHolder[] attachmentData) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subj, "UTF-8");

    Multipart multipart = new MimeMultipart();

    MimeBodyPart bodyMessagePart = new MimeBodyPart();
    bodyMessagePart.setContent(body, TEXT_HTML_CHARSET_UTF_8);

    multipart.addBodyPart(bodyMessagePart);

    attachQRs(multipart, attachmentData);
    attachCSV(multipart, attachmentData);

    message.setContent(multipart);

    Transport.send(message);

    log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body);
}
 
Example #8
Source File: ComposeSimpleMessage.java    From java-course-ee with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        final Properties props = new Properties();
        props.load(ClassLoader.getSystemResourceAsStream("mail.properties"));

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(props.getProperty("smtp.username"), props.getProperty("smtp.pass"));
            }
        });

        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(props.getProperty("address.sender")));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(props.getProperty("address.recipient")));
        message.setSubject("Test JavaMail");

        message.setText("Hello!\n\n\tThis is a test message from JavaMail.\n\nThank you.");

        Transport.send(message);

        log.info("Message was sent");
    }
 
Example #9
Source File: MessageContentTest.java    From subethasmtp with Apache License 2.0 6 votes vote down vote up
/** */
public void testReceivedHeader() throws Exception
{
	MimeMessage message = new MimeMessage(this.session);
	message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	message.setFrom(new InternetAddress("[email protected]"));
	message.setSubject("barf");
	message.setText("body");

	Transport.send(message);

	assertEquals(1, this.wiser.getMessages().size());

	String[] receivedHeaders = this.wiser.getMessages().get(0).getMimeMessage().getHeader("Received");

	assertEquals(1, receivedHeaders.length);
}
 
Example #10
Source File: NotifierBean.java    From eplmp with Eclipse Public License 1.0 6 votes vote down vote up
private void sendEmail(String email, String name, String subject, String content) throws MessagingException {

        if (email == null || email.isEmpty()) {
            LOGGER.log(Level.WARNING, "Cannot send mail, email is empty");
            return;
        }

        try {
            InternetAddress emailAddress = new InternetAddress(email, name);
            Message message = new MimeMessage(mailSession);
            message.addRecipient(Message.RecipientType.TO, emailAddress);
            message.setSubject(subject);
            message.setSentDate(new Date());
            message.setContent(content, "text/html; charset=utf-8");
            message.setFrom();
            Transport.send(message);
        } catch (UnsupportedEncodingException e) {
            String logMessage = "Unsupported encoding: " + e.getMessage();
            LOGGER.log(Level.SEVERE, logMessage, e);
        }
    }
 
Example #11
Source File: MailUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Send a calendar message.
 * 
 * @param mail
 *            The mail to send
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occurred during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException
{
    Message msg = prepareMessage( mail, session );
    msg.setHeader( HEADER_NAME, HEADER_VALUE );

    MimeMultipart multipart = new MimeMultipart( );
    BodyPart msgBodyPart = new MimeBodyPart( );
    msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) );

    multipart.addBodyPart( msgBodyPart );

    BodyPart calendarBodyPart = new MimeBodyPart( );
    calendarBodyPart.setContent( mail.getCalendarMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET )
                    + AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR )
                    + AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) );
    calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 );
    multipart.addBodyPart( calendarBodyPart );

    msg.setContent( multipart );

    sendMessage( msg, transport );
}
 
Example #12
Source File: ServerUtils.java    From sc2gears with Apache License 2.0 6 votes vote down vote up
/**
 * Sends an email.
 * @return true if no error occurred, false otherwise
 */
public static boolean sendEmail( final InternetAddress from, final InternetAddress to, final InternetAddress cc, final String subject, final String body ) {
	LOGGER.info( "Sending email to: " + to.toString() + ", subject: " + subject );
	final Session session = Session.getDefaultInstance( new Properties(), null );
	try {
		final Message message = new MimeMessage( session );
		message.setFrom( from );
		message.addRecipient( Message.RecipientType.TO, to );
		if ( cc != null )
			message.addRecipient( Message.RecipientType.CC, cc );
		message.addRecipient( Message.RecipientType.BCC, ADMIN_EMAIL );
		message.setSubject( "[Sc2gears Database] " + subject );
		message.setText( body );
		Transport.send( message );
		return true;
	} catch ( final Exception e ) {
		LOGGER.log( Level.SEVERE, "Failed to send email!", e );
		return false;
	}
}
 
Example #13
Source File: Emails.java    From chipster with MIT License 6 votes vote down vote up
/**
 * Send a regular email.
 * 
 * @param toEmail receiver's email
 * @param replyTo email for reply or null
 * @param subject
 * @param body
 */
public static void sendEmail(String toEmail, String replyTo, String subject, String body) {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage message = new MimeMessage(session);
    try {
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
        message.setSubject(subject);
        message.setText(body);
        
        // set email for reply
        if (replyTo != null) {
            message.addHeader("Reply-To", replyTo);
        }
        
        Transport.send(message);
    } catch (MessagingException e){
        System.err.println("Email could not be sent.");
    }
}
 
Example #14
Source File: EmailMessagingServiceTest.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
@Test
public void sendAuthenticatedMessage() throws MessagingException, AlertException {
    TestProperties testProperties = new TestProperties();
    EmailProperties emailProperties = new EmailProperties(createEmailGlobalConfigEntity());

    FreemarkerTemplatingService freemarkerTemplatingService = new FreemarkerTemplatingService();
    EmailMessagingService emailMessagingService = new EmailMessagingService(emailProperties, freemarkerTemplatingService);

    Session mockSession = Mockito.mock(Session.class);
    Transport mockTransport = Mockito.mock(Transport.class);

    Mockito.doNothing().when(mockTransport).connect();
    Mockito.doNothing().when(mockTransport).close();
    Mockito.when(mockSession.getTransport(Mockito.anyString())).thenReturn(mockTransport);
    Mockito.when(mockSession.getProperties()).thenReturn(testProperties.getProperties());

    Message message = new MimeMessage(mockSession);
    Mockito.doNothing().when(mockTransport).sendMessage(Mockito.eq(message), Mockito.any());

    emailMessagingService.sendMessages(emailProperties, mockSession, List.of(message));
}
 
Example #15
Source File: Test_MailReportSender.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Test( expected = MailReportSendException.class)
public void errorOnSend() throws MessagingException {

    mockStatic(Transport.class);

    expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator);
    expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost");
    expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25");
    expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[]{ "userTo" });
    expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom");

    Transport.send(isA(Message.class));
    expectLastCall().andThrow(new MessagingException());

    replayAll();

    triggerRun();

    verifyAll();
}
 
Example #16
Source File: Test_MailReportSender.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void sendReport() throws MessagingException {

    mockStatic(Transport.class);

    expect(ReportConfigurator.getInstance()).andReturn(mockReportConfigurator);
    expect(mockReportConfigurator.getSmtpServerName()).andReturn("localhost");
    expect(mockReportConfigurator.getSmtpServerPort()).andReturn("25");
    expect(mockReportConfigurator.getAddressesTo()).andReturn(new String[]{ "userTo" });
    expect(mockReportConfigurator.getAddressesCc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressesBcc()).andReturn(new String[0]);
    expect(mockReportConfigurator.getAddressFrom()).andReturn("userFrom");

    Transport.send(isA(Message.class));

    replayAll();

    triggerRun();

    verifyAll();
}
 
Example #17
Source File: EmailTask.java    From jivejdon with Apache License 2.0 6 votes vote down vote up
/**
 * Runs the task, which sends all email messages that have been queued.
 */
public void run() {
	try {
		Iterator messageIterator = messages.iterator();
		while (messageIterator.hasNext()) {

			try {
				Thread.sleep(6000);
				Message message = (Message) messageIterator.next();
				Transport.send(message);
			} catch (Exception me) {
				me.printStackTrace();
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		this.messages.clear();
	}
}
 
Example #18
Source File: MailNotificationSender.java    From digdag with Apache License 2.0 6 votes vote down vote up
@Override
public void sendNotification(Notification notification)
        throws NotificationException
{
    Session session = createSession();

    MimeMessage msg = new MimeMessage(session);

    try {
        msg.setFrom(newAddress(from));
        msg.setSender(newAddress(from));

        msg.setRecipients(MimeMessage.RecipientType.TO, addresses(this.to));
        msg.setRecipients(MimeMessage.RecipientType.CC, addresses(this.cc));
        msg.setRecipients(MimeMessage.RecipientType.BCC, addresses(this.bcc));

        msg.setSubject(subject);
        msg.setText(body(notification), "utf-8", isHtml ? "html" : "plain");
        Transport.send(msg);
    }
    catch (MessagingException | IOException | TemplateException ex) {
        throw Throwables.propagate(ex);
    }
}
 
Example #19
Source File: ConnectionStrategyFactory.java    From smtp-connection-pool with Apache License 2.0 6 votes vote down vote up
public static ConnectionStrategy newConnectionStrategy(final String username, final String password) {
  return new ConnectionStrategy() {
    @Override
    public void connect(Transport transport) throws MessagingException {
      transport.connect(username, password);
    }

    @Override
    public String toString() {
      return "ConnectionStrategy{" +
          "username=" + username +
          '}';
    }

  };
}
 
Example #20
Source File: GMail.java    From TwrpBuilder with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
@Override
protected String doInBackground(String... strings) {
    try {
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes()));
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        message.setDataHandler(handler);
        if (recipients.indexOf(',') > 0)
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        Transport.send(message);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #21
Source File: EmailNotifier.java    From streamline with Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link Transport} object from the session registering the passed in transport listener
 * for delivery notifications.
 */
private Transport getEmailTransport(Session session, TransportListener listener) {
    try {
        Transport transport = session.getTransport();
        transport.addTransportListener(listener);
        if (!transport.isConnected()) {
            transport.connect();
        }
        LOG.debug("Email transport {}, transport listener {}", transport, listener);
        return transport;
    } catch (MessagingException ex) {
        LOG.error("Got exception while initializing transport", ex);
        throw new NotifierRuntimeException("Got exception while initializing transport", ex);
    }
}
 
Example #22
Source File: EmailSender.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends e-mail to the specified recipients.
 * 
 * @param recipients
 *            Comma separated list of recipient e-mail addresses
 * @param subject
 *            Subject for the e-mail
 * @param messageBody
 *            The body for the e-mail
 */
public void send(String recipients, String subject, String messageBody) {
	Message message = new MimeMessage(session);
	
	try {

		message.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(recipients));
		message.setSubject(subject);
		message.setText(messageBody);

		Transport.send(message);

		logger.info("Successfully sent e-mail to {} . The e-mail "
				+ "message subject was: \"{}\", and body was: \"{}\"", 
				recipients, subject, messageBody);
	} catch (MessagingException e) {
		// Since this is a serious issue log the error and send an e-mail 
		// via logback
		logger.error(Markers.email(), 
				"Failed sending e-mail for agencyId={}. The e-mail config "
				+ "file {} specified by the Java property {} contains the "
				+ "login info to the SMTP server. Exception message: {}. "
				+ "The e-mail message subject was: \"{}\", and body "
				+ "was: \"{}\"",
				AgencyConfig.getAgencyId(), emailConfigFile.getID(), 
				emailConfigFile.getValue(),	e.getMessage(), subject, 
				messageBody);
	}
}
 
Example #23
Source File: MailService.java    From commafeed with Apache License 2.0 5 votes vote down vote up
public void sendMail(User user, String subject, String content) throws Exception {

		ApplicationSettings settings = config.getApplicationSettings();

		final String username = settings.getSmtpUserName();
		final String password = settings.getSmtpPassword();
		final String fromAddress = Optional.ofNullable(settings.getSmtpFromAddress()).orElse(settings.getSmtpUserName());

		String dest = user.getEmail();

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "" + settings.isSmtpTls());
		props.put("mail.smtp.host", settings.getSmtpHost());
		props.put("mail.smtp.port", "" + settings.getSmtpPort());

		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(username, password);
			}
		});

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(fromAddress, "CommaFeed"));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(dest));
		message.setSubject("CommaFeed - " + subject);
		message.setContent(content, "text/html; charset=utf-8");

		Transport.send(message);

	}
 
Example #24
Source File: AlfrescoJavaMailSender.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Checks to see if the pooled {@link Transport} is still connected.
 * 
 * @param key {@link URLName} containing the connection details.
 * @param object Pooled {@link Transport}
 * 
 * @return true if the pooled transport is still connected, or false,  otherwise.
 */
@Override
public boolean validateObject(Object key, Object object)
{
    if (object instanceof Transport == false)
    {
        throw new IllegalArgumentException("Unexpected object type");
    }
    log.debug("Validating transport");
    Transport transport = (Transport)object;
    return transport.isConnected();
}
 
Example #25
Source File: AbstractMailSenderFactory.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 以文本格式发送邮件.
 *
 * @param mailSender 待发送的邮件的信息
 * @return Boolean
 */
protected boolean sendTextMail(final AbstractMailSender mailSender) {
    final Properties pro = mailSender.getProperties();
    MailAuthenticator authenticator = null;
    if (mailSender.isValidate()) {
        authenticator = new MailAuthenticator(mailSender.getUserName(), mailSender.getPassword());
    }
    
    final Session sendMailSession;
    if(singletonSessionInstance) {
        sendMailSession = Session.getDefaultInstance(pro, authenticator);
    } else {
        sendMailSession = Session.getInstance(pro, authenticator);
    }
    
    sendMailSession.setDebug(debugEnabled);
    try {
        final Message mailMessage = new MimeMessage(sendMailSession);
        final Address from = new InternetAddress(mailSender.getFromAddress());
        mailMessage.setFrom(from);
        mailMessage.setRecipients(Message.RecipientType.TO, toAddresses(mailSender.getToAddress()));
        mailMessage.setSubject(mailSender.getSubject());
        mailMessage.setSentDate(new Date());
        mailMessage.setText(mailSender.getContent());
        Transport.send(mailMessage);
        return true;
    } catch (final MessagingException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    
    return false;
}
 
Example #26
Source File: JavaMailSenderImpl.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Obtain a Transport object from the given JavaMail Session,
 * using the configured protocol.
 * <p>Can be overridden in subclasses, e.g. to return a mock Transport object.
 * @see javax.mail.Session#getTransport(String)
 * @see #getSession()
 * @see #getProtocol()
 */
protected Transport getTransport(Session session) throws NoSuchProviderException {
	String protocol	= getProtocol();
	if (protocol == null) {
		protocol = session.getProperty("mail.transport.protocol");
		if (protocol == null) {
			protocol = DEFAULT_PROTOCOL;
		}
	}
	return session.getTransport(protocol);
}
 
Example #27
Source File: JavaMailSenderImpl.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Obtain and connect a Transport from the underlying JavaMail Session,
 * passing in the specified host, port, username, and password.
 * @return the connected Transport object
 * @throws MessagingException if the connect attempt failed
 * @since 4.1.2
 * @see #getTransport
 * @see #getHost()
 * @see #getPort()
 * @see #getUsername()
 * @see #getPassword()
 */
protected Transport connectTransport() throws MessagingException {
	String username = getUsername();
	String password = getPassword();
	if ("".equals(username)) {  // probably from a placeholder
		username = null;
		if ("".equals(password)) {  // in conjunction with "" username, this means no password to use
			password = null;
		}
	}

	Transport transport = getTransport(getSession());
	transport.connect(getHost(), getPort(), username, password);
	return transport;
}
 
Example #28
Source File: AlfrescoJavaMailSender.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a new {@link Transport} using the {@link Session} returned by {@link JavaMailSenderImpl#getSession() getSession()}.
 * 
 * @param key A {@link URLName} containing the connection details
 * @return A new {@link Transport}
 */
@Override
public Object makeObject(Object key) throws Exception
{
    if ((key instanceof URLName) == false)
    {
        throw new IllegalArgumentException("Invlid key type");
    }
    log.debug("Creating new Transport");
    URLName urlName = (URLName) key;
    Transport transport = getSession().getTransport(urlName.getProtocol()); 
    transport.connect(urlName.getHost(), urlName.getPort(), urlName.getUsername(), urlName.getPassword());
    return transport;
}
 
Example #29
Source File: GMailSender.java    From vocefiscal-android with Apache License 2.0 5 votes vote down vote up
public boolean send() throws Exception 
{ 
  Properties props = setProperties(); 

  if(!user.equals("") && !pass.equals("") && to.length > 0 && !from.equals("") && !subject.equals("") && !body.equals("")) 
  { 
    Session session = Session.getInstance(props, this); 

    MimeMessage msg = new MimeMessage(session); 

    msg.setFrom(new InternetAddress(from)); 

    InternetAddress[] addressTo = new InternetAddress[to.length]; 
    for (int i = 0; i < to.length; i++) 
    { 
      addressTo[i] = new InternetAddress(to[i]); 
    } 
      msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); 

    msg.setSubject(subject); 
    msg.setSentDate(new Date()); 

    // setup message body 
    BodyPart messageBodyPart = new MimeBodyPart(); 
    messageBodyPart.setText(body); 
    multipart.addBodyPart(messageBodyPart); 

    // Put parts in message 
    msg.setContent(multipart); 

    // send email 
    Transport.send(msg); 

    return true; 
  } else 
  { 
    return false; 
  } 
}
 
Example #30
Source File: SendMailAnnotationListener.java    From jetstream-esper with GNU General Public License v2.0 5 votes vote down vote up
@Override
public JetstreamEvent processMetaInformation(JetstreamEvent event,
		StatementAnnotationInfo annotationInfo) {
	
	SendMailAnnotationMetadata anntmetadata = (SendMailAnnotationMetadata) annotationInfo.getAnnotationInfo(ANNO_KEY);
	properties = new Properties();
	properties.setProperty("mail.smtp.host", anntmetadata.getMailServer());

      Session session = Session.getInstance(properties, null); 
      try{
          MimeMessage message = new MimeMessage(session);
          message.addHeader("Content-type", "text/HTML; charset=UTF-8");
          
          message.setFrom(new InternetAddress(anntmetadata.getSendFrom()));
          
          message.setRecipients(Message.RecipientType.TO,
        		  InternetAddress.parse(anntmetadata.getAlertList(), false));
          
          String[] fieldList = anntmetadata.getEventFields().split(",");
		  StringBuffer sb = new StringBuffer();
		  sb.append(anntmetadata.getMailContent()).append(".\n");
          for(int i=0; i<fieldList.length;i++){
        	  sb.append(fieldList[i]).append(": ").append(event.get(fieldList[i])).append(",\n");
          }
		  message.setText(sb.toString(), "UTF-8");	
		  
		  StringBuffer subject = new StringBuffer();
		  if(anntmetadata.getAlertSeverity() != null)
			  subject.append(anntmetadata.getAlertSeverity()).append(" alert for Jetstream Event Type").append(event.getEventType()).append(": ");
		  if(anntmetadata.getMailSubject() != "")
			  subject.append(anntmetadata.getMailSubject());
		  message.setSubject(subject.toString(), "UTF-8");

          Transport.send(message);
       }catch (Throwable mex) {
          s_logger.warn( mex.getLocalizedMessage());
       }
	return event;
}