javax.mail.Session Java Examples

The following examples show how to use javax.mail.Session. 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: MailUtil.java    From anyline with Apache License 2.0 7 votes vote down vote up
/** 
 *  
 * @param fr		发送人姓名  fr		发送人姓名
 * @param to		收件人地址  to		收件人地址
 * @param title		邮件主题  title		邮件主题
 * @param content	邮件内容  content	邮件内容
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][content:{}]", fr,to,title,content);
	try { 
		Session mailSession = Session.getDefaultInstance(props); 
		Message msg = new MimeMessage(mailSession); 
		msg.setFrom(new InternetAddress(config.ACCOUNT,fr)); 
		msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); 
		msg.setSubject(title + ""); 
		msg.setContent(content + "", "text/html;charset=UTF-8"); 
		msg.saveChanges(); 
		Transport transport = mailSession.getTransport("smtp"); 
		transport.connect(config.HOST,
				config.ACCOUNT, 
				config.PASSWORD);
		transport.sendMessage(msg, msg.getAllRecipients()); 
		transport.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
		return false; 
	} 

	return true; 
}
 
Example #2
Source File: Pop3Util.java    From anyline with Apache License 2.0 7 votes vote down vote up
/** 
 *  
 * @param fr 发送人姓名 
 * @param to 收件人地址 
 * @param title 邮件主题 
 * @param content  邮件内容 
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][centent:{}]", fr, to, title, content); 
	try { 
		Session mailSession = Session.getDefaultInstance(props); 
		Message msg = new MimeMessage(mailSession); 
		msg.setFrom(new InternetAddress(config.ACCOUNT, fr)); 
		msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); 
		msg.setSubject(title); 
		msg.setContent(content, "text/html;charset=UTF-8"); 
		msg.saveChanges(); 
		Transport transport = mailSession.getTransport("smtp"); 
		transport.connect(config.HOST, config.ACCOUNT, config.PASSWORD); 
		transport.sendMessage(msg, msg.getAllRecipients()); 
		transport.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
		return false; 
	} 

	return true; 
}
 
Example #3
Source File: PollMailConnectorTest.java    From camunda-bpm-mail with Apache License 2.0 7 votes vote down vote up
@Test
public void htmlMessage() throws MessagingException {
  greenMail.setUser("[email protected]", "bpmn");

  Session session = greenMail.getSmtp().createSession();
  MimeMessage message = MailTestUtil.createMimeMessageWithHtml(session);

  GreenMailUtil.sendMimeMessage(message);

  PollMailResponse response = MailConnectors.pollMails()
    .createRequest()
      .folder("INBOX")
    .execute();

  List<Mail> mails = response.getMails();
  assertThat(mails).hasSize(1);

  Mail mail = mails.get(0);
  assertThat(mail.getHtml()).isEqualTo("<b>html</b>");
  assertThat(mail.getText()).isEqualTo("text");
}
 
Example #4
Source File: SmtpJmsTransportTest.java    From javamail with Apache License 2.0 7 votes vote down vote up
@Test
public void testDoNotCheckFormHeader() throws Exception {
    Properties properties = new Properties();
    properties.setProperty("mail.smtpjms.validateFrom", "false");
    SmtpJmsTransport transport = new SmtpJmsTransport(Session.getInstance(properties), new URLName("jms"));
    Message message = Mockito.mock(Message.class);
    TransportListener listener = Mockito.mock(TransportListener.class);
    Address[] to = new Address[]{ new InternetAddress("[email protected]") };
    transport.addTransportListener(listener);
    transport.sendMessage(message, to);
    waitForListeners();
    ArgumentCaptor<TransportEvent> transportEventArgumentCaptor = ArgumentCaptor.forClass(TransportEvent.class);
    verify(listener).messageDelivered(transportEventArgumentCaptor.capture());
    TransportEvent event = transportEventArgumentCaptor.getValue();
    assertEquals(message, event.getMessage());
    assertEquals(TransportEvent.MESSAGE_DELIVERED, event.getType());
    assertArrayEquals(to, event.getValidSentAddresses());
}
 
Example #5
Source File: MailSenderTestBase.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Test
public void mailWithPRC() throws Exception {
	String mailInput = "<email/>";

	appendParameters(sender);

	sender.configure();
	sender.open();

	sender.sendMessage(new Message(mailInput), session);
	Session mailSession = (Session) session.get("mailSession");
	assertEquals("localhost", mailSession.getProperty("mail.smtp.host"));

	MimeMessage message = (MimeMessage) mailSession.getProperties().get("MimeMessage");
	validateAuthentication(mailSession);
	compare("mailWithPRC.txt", message);
}
 
Example #6
Source File: MailManager.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean send(String text, String subject, String[] recipientsTo, String[] recipientsCc, String[] recipientsBcc, String senderCode, Properties attachmentFiles, String contentType) throws ApsSystemException {
	Transport bus = null;
	try {
		Session session = this.prepareSession(this.getConfig());
		bus = this.prepareTransport(session, this.getConfig());
		MimeMessage msg = this.prepareVoidMimeMessage(session, subject, recipientsTo, recipientsCc, recipientsBcc, senderCode);
		if (attachmentFiles == null || attachmentFiles.isEmpty()) {
			msg.setContent(text, contentType + "; charset=utf-8");
		} else {
			Multipart multiPart = new MimeMultipart();
			this.addBodyPart(text, contentType, multiPart);
			this.addAttachments(attachmentFiles, multiPart);
			msg.setContent(multiPart);
		}
		msg.saveChanges();
		bus.send(msg);
	} catch (Throwable t) {
		throw new ApsSystemException("Error sending mail", t);
	} finally {
		closeTransport(bus);
	}
	return true;
}
 
Example #7
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 #8
Source File: MailSenderSMTP.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void sendEmail(String address, String subject, String content, Map<String, String> headers,
					  UnaryOperator<String> properties) throws Exception {
	Session session = MailUtilities.makeSession(properties);
	if (session == null) {
		LogService.getRoot().log(Level.WARNING, SESSION_CREATION_FAILURE, address);
	}
	MimeMessage msg = new MimeMessage(session);
	msg.setRecipients(Message.RecipientType.TO, address);
	msg.setFrom();
	msg.setSubject(subject, "UTF-8");
	msg.setSentDate(new Date());
	msg.setText(content, "UTF-8");

	if (headers != null) {
		for (Entry<String, String> header : headers.entrySet()) {
			msg.setHeader(header.getKey(), header.getValue());
		}
	}
	Transport.send(msg);
}
 
Example #9
Source File: DKIMVerifyTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
private Mail process(String message) throws Exception {
    Mailet mailet = new DKIMVerify((new MockPublicKeyRecordRetriever(
        "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYDaYKXzwVYwqWbLhmuJ66aTAN8wmDR+rfHE8HfnkSOax0oIoTM5zquZrTLo30870YMfYzxwfB6j/Nz3QdwrUD/t0YMYJiUKyWJnCKfZXHJBJ+yfRHr7oW+UW3cVo9CG2bBfIxsInwYe175g9UjyntJpWueqdEIo1c2bhv9Mp66QIDAQAB;",
        "selector", "example.com")));

    FakeMailetConfig mci = FakeMailetConfig.builder()
            .mailetName("Test")
            .mailetContext(FakeMailContext.defaultContext())
            .build();

    mailet.init(mci);

    Mail mail = FakeMail.builder()
        .name("test")
        .mimeMessage(new MimeMessage(Session
            .getDefaultInstance(new Properties()),
            new ByteArrayInputStream(message.getBytes())))
        .build();

    mailet.service(mail);
    return mail;
}
 
Example #10
Source File: GreenMailServer.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Get the connection to a mail store
 *
 * @param user     whose mail store should be connected
 * @param protocol protocol used to connect
 * @return
 * @throws MessagingException when unable to connect to the store
 */
private static Store getConnection(GreenMailUser user, String protocol) throws MessagingException {
    Properties props = new Properties();
    Session session = Session.getInstance(props);
    int port;
    if (PROTOCOL_POP3.equals(protocol)) {
        port = 3110;
    } else if (PROTOCOL_IMAP.equals(protocol)) {
        port = 3143;
    } else {
        port = 3025;
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "localhost");
        props.put("mail.smtp.port", "3025");
    }
    URLName urlName = new URLName(protocol, BIND_ADDRESS, port, null, user.getLogin(), user.getPassword());
    Store store = session.getStore(urlName);
    store.connect();
    return store;
}
 
Example #11
Source File: SendEmailToUser.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 6 votes vote down vote up
public void setReadyForEmail(String username, String password) {
	props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.socketFactory.port", "465");
	props.put("mail.smtp.socketFactory.class",
			"javax.net.ssl.SSLSocketFactory");
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.port", "465");
	
	Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				@Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(username, password);
				}
			});
	
	message = new MimeMessage(session);
}
 
Example #12
Source File: MailHandlerServlet.java    From appengine-tck with Apache License 2.0 6 votes vote down vote up
/**
 * Stores subject and headers into memcache for test to confirm mail delivery.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    try {
        MimeMessage message = new MimeMessage(session, req.getInputStream());
        MimeProperties mp = new MimeProperties(message);

        List<String> headers = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        Enumeration e = message.getAllHeaderLines();
        while (e.hasMoreElements()) {
            String headerLine = (String) e.nextElement();
            headers.add(headerLine);
            sb.append("\n").append(headerLine);
        }
        log.info("HEADERS: " + sb.toString());

        mp.headers = headers.toString();
        TestBase.putTempData(mp);
    } catch (MessagingException me) {
        throw new IOException("Error while processing email.", me);
    }
}
 
Example #13
Source File: ImapConnector.java    From bobcat with Apache License 2.0 6 votes vote down vote up
protected void connectWithProtocol(String protocol) {
  try {
    Properties properties = new Properties();
    properties.setProperty("mail.store.protocol", protocol);
    Session session = Session.getDefaultInstance(properties, null);
    store = session.getStore(protocol);
    store.connect(configuration.getServer(), configuration.getPort(),
        configuration.getUsername(),
        configuration.getPassword());
    folder = store.getFolder(configuration.getFolderName());
    folder.open(Folder.READ_WRITE);

  } catch (MessagingException e) {
    LOG.error("error - cannot connect to mail server", e);
    throw new ConnectorException(e);
  }
}
 
Example #14
Source File: EMailManager.java    From jforgame with Apache License 2.0 6 votes vote down vote up
/**
 * 创建一封只包含文本的简单邮件
 *
 * @param session     和服务器交互的会话
 * @param sendMail    发件人邮箱
 * @param receiveMail 收件人邮箱
 * @return
 * @throws Exception
 */
private MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String title, String content) throws Exception {
	// 1. 创建一封邮件
	MimeMessage message = new MimeMessage(session);

	// 2. From: 发件人
	message.setFrom(new InternetAddress(sendMail, "昵称", "UTF-8"));

	// 3. To: 收件人(可以增加多个收件人、抄送、密送)
	message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "XX用户", "UTF-8"));

	// 4. Subject: 邮件主题
	message.setSubject(title, "UTF-8");

	// 5. Content: 邮件正文(可以使用html标签)
	message.setContent(content, "text/html;charset=UTF-8");
	// 6. 设置发件时间
	message.setSentDate(new Date());

	// 7. 保存设置
	message.saveChanges();

	return message;
}
 
Example #15
Source File: GoogleMailResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
private Message createMessage(String body) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);

    Profile profile = producerTemplate.requestBody("google-mail://users/getProfile?inBody=userId", USER_ID, Profile.class);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(TO, profile.getEmailAddress());
    mm.setSubject(EMAIL_SUBJECT);
    mm.setContent(body, "text/plain");

    Message message = new Message();
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        mm.writeTo(baos);
        message.setRaw(Base64.getUrlEncoder().encodeToString(baos.toByteArray()));
    }
    return message;
}
 
Example #16
Source File: MailSenderTestBase.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Test
public void mailWithBase64Message() throws Exception {
	String mailInput = "<email>"
			+ "<recipients>"
				+ "<recipient type=\"to\" name=\"dummy\">[email protected]</recipient>"
			+ "</recipients>"
			+ "<subject>My Subject</subject>"
			+ "<from name=\"Me, Myself and I\">[email protected]</from>"
			+ "<message>VGhpcyBpcyBhIHRlc3QgZmlsZS4=</message>"
			+ "<messageType>text/plain</messageType>"
			+ "<replyTo>[email protected]</replyTo>"
			+ "<charset>UTF-8</charset>"
			+ "<messageBase64>true</messageBase64>"
		+ "</email>";

	sender.configure();
	sender.open();

	sender.sendMessage(new Message(mailInput), session);
	Session mailSession = (Session) session.get("mailSession");
	assertEquals("localhost", mailSession.getProperty("mail.smtp.host"));

	MimeMessage message = (MimeMessage) mailSession.getProperties().get("MimeMessage");
	validateAuthentication(mailSession);
	compare("mailWithBase64Message.txt", message);
}
 
Example #17
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 #18
Source File: EmailNotificationService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
 *
 * @param properties mail properties
 * @return session
 */
private Session createMailSession(final Properties properties) {
    String authValue = properties.getProperty("mail.smtp.auth");
    Boolean auth = Boolean.valueOf(authValue);

    /*
     * Conditionally create a password authenticator if the 'auth' parameter is set.
     */
    final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
            return new PasswordAuthentication(username, password);
        }
    }) : Session.getInstance(properties); // without auth

    return mailSession;
}
 
Example #19
Source File: EmailNotifierBase.java    From DotCi with MIT License 6 votes vote down vote up
public MimeMessage createEmail(DynamicBuild build, BuildListener listener) throws AddressException, MessagingException {
    List<InternetAddress> to = getToEmailAddress(build, listener);

    String from = SetupConfig.get().getFromEmailAddress();
    Session session = Session.getDefaultInstance(System.getProperties());
    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));

    message.addRecipients(Message.RecipientType.TO, to.toArray(new InternetAddress[to.size()]));

    String subject = getNotificationMessage(build, listener);
    message.setSubject(subject);
    message.setText("Link to the build " + build.getAbsoluteUrl());
    return message;
}
 
Example #20
Source File: NntpUtil.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
public  static String getArticleBody(NNTPClient client, long articleNumber)
	throws IOException {
	String articleBody = null;
	//We convert the full message into a MIME message for getting exactly the text message clean
	Reader reader = (DotTerminatedMessageReader) client.retrieveArticle(articleNumber);
	if (reader != null) {
		InputStream inputStream = new ByteArrayInputStream(CharStreams.toString(reader).getBytes(Charsets.UTF_8));
		try {
			Session session = Session.getInstance(new Properties());	//For parsing the messages correctly
			MimeMessage message = new MimeMessage(session, inputStream);
			Object contentObject = message.getContent();
			if(!(contentObject instanceof MimeMultipart))
				articleBody = (String)contentObject;
			else
				articleBody = getBodyPart((MimeMultipart) contentObject);
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} else {
		return articleBody;
	}
	return articleBody;
}
 
Example #21
Source File: SendMailConnector.java    From camunda-bpm-mail with Apache License 2.0 6 votes vote down vote up
protected Message createMessage(SendMailRequest request, Session session) throws Exception {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(request.getFrom(), request.getFromAlias()));
    message.setRecipients(RecipientType.TO, InternetAddress.parse(request.getTo()));

    if (request.getCc() != null) {
      message.setRecipients(RecipientType.CC, InternetAddress.parse(request.getCc()));
    }
    if (request.getBcc() != null) {
      message.setRecipients(RecipientType.BCC, InternetAddress.parse(request.getBcc()));
    }

    message.setSentDate(new Date());
    message.setSubject(request.getSubject());

    if (hasContent(request)) {
      createMessageContent(message, request);
    } else {
      message.setText("");
    }

    return message;
  }
 
Example #22
Source File: MailSender.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 创建 session.
 */
private void createSession() {
	session = Session.getInstance(props, new Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(userName, password);
		}
	});
	session.setDebug(true);
}
 
Example #23
Source File: EmailTest.java    From light with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        final String username = "[email protected]";
        final String password = "sxwt2ysc";

        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", "mail.networknt.com");
        props.put("mail.smtp.port", "587");

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

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("[email protected]"));
            message.setSubject("Testing Subject");
            message.setContent("Hi,<br>Thanks for registering with us.<br>Please use the following <a href='http://www.networknt.com/api/rs?cmd={\"readOnly\":true,\"category\":\"user\",\"name\":\"activateUser\"}'>link</a> to activate your account.", "text/html; charset=utf-8");
            Transport.send(message);

            System.out.println("Done");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
 
Example #24
Source File: CubaMailSender.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Session getSession() {
    if (!propertiesInitialized) {
        Properties properties = createJavaMailProperties();
        setJavaMailProperties(properties);
        propertiesInitialized = true;
    }
    return super.getSession();
}
 
Example #25
Source File: LiveChatBean.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public void sendEmail(final String address, final String subject, final String text,  final String html) {
	Store store = null;
	try {
		Stats.stats.emails++;
		AdminDatabase.instance().log(Level.INFO, "Sending email", address, subject);
        //store = connectStore();
		Session session = connectSession();

		MimeMessage message = new MimeMessage(session);
	    message.setFrom(new InternetAddress(this.instance.getEmailAddress()));
	    message.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
	    message.setSubject(subject);
	    if (html != null) {
		    message.setContent(html, "text/html; charset=UTF-8");
	    } else {
	    	message.setText(text);
	    }

	    // Send message
	    Transport.send(message);
	} catch (Throwable messagingException) {
		AdminDatabase.instance().log(messagingException);
		error(messagingException);
	} finally {
		try {
			if (store != null) {
				store.close();
			}
		} catch (Exception ignore) {}
	}
}
 
Example #26
Source File: AbstractFileTransport.java    From javamail with Apache License 2.0 5 votes vote down vote up
AbstractFileTransport(Session session, URLName urlname) {
	super(session, urlname);
	String s = session.getProperties().getProperty("mail.files.path", ".");
	directory = new File(s);
	if (! directory.exists() && ! directory.mkdirs()) {
           throw new IllegalArgumentException("Unable to create output directory " + directory.getAbsolutePath());
	}
}
 
Example #27
Source File: MailManager.java    From mail-micro-service with Apache License 2.0 5 votes vote down vote up
public static void putBoth(String key, Properties properties){
    putProperties(key, properties);
    // 此处要用 Session#getInstance,Session#getDefaultInstance 为单例
    Session session = Session.getInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(properties.getProperty("mail.username"),
                    properties.getProperty("mail.password"));
        }
    });
    if(null != properties.getProperty("mail.debug")){
        session.setDebug(Boolean.valueOf(properties.getProperty("mail.debug")));
    }
    putSession(key, session);
}
 
Example #28
Source File: CallableScript.java    From chronos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CallableScript(PlannedJob plannedJob, JobDao dao,
                     Reporting reporting, long jobId, String hostname,
                     MailInfo mailInfo, Session session,
                     int attemptNumber) {
  this.plannedJob = plannedJob;
  this.dao = dao;
  this.reporting = reporting;
  this.jobId = jobId;
  this.mailInfo = mailInfo;
  this.session = session;
  this.attemptNumber = attemptNumber;
  setReplacedCode();
  runner = new BashRunner();
  runner.init();
}
 
Example #29
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 #30
Source File: WiserFailuresTest.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
private MimeMessage createMessage(Session session, String from, String to, String subject, String body)
	throws MessagingException, IOException
{
	MimeMessage msg = new MimeMessage(session);
	msg.setFrom(new InternetAddress(from));
	msg.setSubject(subject);
	msg.setSentDate(new Date());
	msg.setText(body);
	msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
	return msg;
}