Java Code Examples for javax.mail.Session#getDefaultInstance()

The following examples show how to use javax.mail.Session#getDefaultInstance() . 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: 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 2
Source File: SmartSendMailUtil.java    From smart-admin with MIT License 6 votes vote down vote up
/**
 * 创建session
 *
 * @author lidoudou
 * @date 2019/2/16 14:59
 */
private static Session createSSLSession(String sendSMTPHost, String port, String userName, String pwd) {
    // 1. 创建参数配置, 用于连接邮件服务器的参数配置
    Properties props = new Properties(); // 参数配置

    props.setProperty("mail.smtp.user", userName);
    props.setProperty("mail.smtp.password", pwd);
    props.setProperty("mail.smtp.host", sendSMTPHost);
    props.setProperty("mail.smtp.port", port);
    props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.socketFactory.port", port);
    props.put("mail.smtp.auth", "true");

    // 2. 根据配置创建会话对象, 用于和邮件服务器交互
    Session session = Session.getDefaultInstance(props, new Authenticator() {
        //身份认证
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, pwd);
        }
    });
    session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
    return session;
}
 
Example 3
Source File: JavamailService.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public MimeMessage parseToEmail(EmailWrapper wrapper) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage email = new MimeMessage(session);
    if (wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()) {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail()));
    } else {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail(), wrapper.getSenderName()));
    }
    email.setReplyTo(new Address[] { new InternetAddress(wrapper.getReplyTo()) });
    email.addRecipient(Message.RecipientType.TO, new InternetAddress(wrapper.getRecipient()));
    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        email.addRecipient(Message.RecipientType.BCC, new InternetAddress(wrapper.getBcc()));
    }
    email.setSubject(wrapper.getSubject());
    email.setContent(wrapper.getContent(), "text/html");
    return email;
}
 
Example 4
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 5
Source File: MimeMessageParserTest.java    From commons-email with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseInlineCID() throws Exception
{
    final Session session = Session.getDefaultInstance(new Properties());
    final MimeMessage message = MimeMessageUtils.createMimeMessage(session, new File("./src/test/resources/eml/html-attachment.eml"));
    final MimeMessageParser mimeMessageParser = new MimeMessageParser(message);

    mimeMessageParser.parse();

    assertEquals("Test", mimeMessageParser.getSubject());
    assertNotNull(mimeMessageParser.getMimeMessage());
    assertTrue(mimeMessageParser.isMultipart());
    assertTrue(mimeMessageParser.hasHtmlContent());
    assertNotNull(mimeMessageParser.getHtmlContent());
    assertTrue(mimeMessageParser.getTo().size() == 1);
    assertTrue(mimeMessageParser.getCc().size() == 0);
    assertTrue(mimeMessageParser.getBcc().size() == 0);
    assertEquals("[email protected]", mimeMessageParser.getFrom());
    assertEquals("[email protected]", mimeMessageParser.getReplyTo());
    assertTrue(mimeMessageParser.hasAttachments());

    assertTrue(mimeMessageParser.getContentIds().contains("[email protected]"));
    assertFalse(mimeMessageParser.getContentIds().contains("part2"));

    final DataSource ds = mimeMessageParser.findAttachmentByCid("[email protected]");
    assertNotNull(ds);
    assertEquals(ds, mimeMessageParser.getAttachmentList().get(0));
}
 
Example 6
Source File: TestSMTPServerTest.java    From OrigamiSMTP with MIT License 5 votes vote down vote up
private void sendTestMessage() throws AddressException, MessagingException
{
           Properties props = System.getProperties();
           props.put("mail.smtp.host","localhost");
           props.put("mail.smtp.port","2525");
           props.put("mail.smtp.socketFactory.port","2525");
           //props.put("mail.smtp.starttls.enable","true");
           Session session = Session.getDefaultInstance(props);
           MimeMessage msg = new MimeMessage(session);
           msg.setFrom(new InternetAddress("[email protected]"));
           msg.setRecipient(javax.mail.Message.RecipientType.TO,new InternetAddress("[email protected]"));
           msg.setSubject("Test email");
           msg.setText("Hello!");
           Transport.send(msg);
}
 
Example 7
Source File: SimpleMailSender.java    From KJFrameForAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 以文本格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件的信息
 */
public boolean sendTextMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(),
                mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session
            .getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
 
Example 8
Source File: SmtpJmsTransportTest.java    From javamail with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendInvalidPriority() throws Exception {
    SmtpJmsTransport transport = new SmtpJmsTransport(Session.getDefaultInstance(new Properties()), new URLName("jsm"));
    Message message = Mockito.mock(Message.class);
    when(message.getHeader(eq(SmtpJmsTransport.X_SEND_PRIORITY))).thenReturn(new String[]{"invalid"});
    when(message.getFrom()).thenReturn(new Address[] { new InternetAddress("[email protected]") });
    transport.sendMessage(message, new Address[] { new InternetAddress("[email protected]") });
    verify(bytesMessage, never()).setJMSPriority(anyInt());
}
 
Example 9
Source File: SSLEmail.java    From journaldev with MIT License 5 votes vote down vote up
/**
   Outgoing Mail (SMTP) Server
   requires TLS or SSL: smtp.gmail.com (use authentication)
   Use Authentication: Yes
   Port for SSL: 465
 */
public static void main(String[] args) {
	final String fromEmail = "[email protected]";
	final String password = "my_pwd";
	final String toEmail = "[email protected]";
	
	System.out.println("SSLEmail Start");
	Properties props = new Properties();
	props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
	props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
	props.put("mail.smtp.socketFactory.class",
			"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
	props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
	props.put("mail.smtp.port", "465"); //SMTP Port
	
	Authenticator auth = new Authenticator() {
		//override the getPasswordAuthentication method
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(fromEmail, password);
		}
	};
	
	Session session = Session.getDefaultInstance(props, auth);
	System.out.println("Session created");
    EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");

    EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");

    EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");

}
 
Example 10
Source File: MimeMessageWrapper.java    From james-project with Apache License 2.0 4 votes vote down vote up
private MimeMessageWrapper() {
    super(Session.getDefaultInstance(new Properties()));
}
 
Example 11
Source File: ImapMessageTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testEncodedFromToAddresses() throws Exception
{
    // RFC1342
    String addressString = "[email protected]";
    String personalString = "�?р�?ений Ковальчук";
    InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8");
    
    // Following method returns the address with quoted personal aka <["�?р�?ений Ковальчук"] <[email protected]>>
    // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? 
    // String decodedAddress = address.toUnicodeString();
    // Starting from javax.mail 1.5.6 the address is folded at linear whitespace so that each line is no longer than 76 characters, if possible.
    String decodedAddress = MimeUtility.decodeText(MimeUtility.fold(6, address.toString()));
    
    // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter
    // So, compare with that
    assertFalse("Non ASCII characters in the address should be encoded", decodedAddress.equals(InternetAddress.toString(new Address[] {address})));
    
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    
    MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");
    
    messageHelper.setText("This is a sample message for ALF-5647");
    messageHelper.setSubject("This is a sample message for ALF-5647");
    messageHelper.setFrom(address);
    messageHelper.addTo(address);
    messageHelper.addCc(address);
    
    // Creating the message node in the repository
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT);
    // Writing a content.
    new IncomingImapMessage(messageFile, serviceRegistry, message);
    
    // Getting the transformed properties from the repository
    // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc
    Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef());
    
    String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR);
    String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
    @SuppressWarnings("unchecked")
    List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES);
    String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM);
    String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO);
    String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC);
    
    assertNotNull(cmOriginator);
    assertEquals(decodedAddress, cmOriginator);
    assertNotNull(cmAddressee);
    assertEquals(decodedAddress, cmAddressee);
    assertNotNull(cmAddressees);
    assertEquals(1, cmAddressees.size());
    assertEquals(decodedAddress, cmAddressees.get(0));
    assertNotNull(imapMessageFrom);
    assertEquals(decodedAddress, imapMessageFrom);
    assertNotNull(imapMessageTo);
    assertEquals(decodedAddress, imapMessageTo);
    assertNotNull(imapMessageCc);
    assertEquals(decodedAddress, imapMessageCc);
}
 
Example 12
Source File: EmailUtil.java    From Insights with Apache License 2.0 4 votes vote down vote up
public void sendEmail(Mail mail,EmailConfiguration emailConf, String emailBody) throws MessagingException,
																				IOException,UnsupportedEncodingException {

	Properties props = System.getProperties();
	props.put(EmailConstants.SMTPHOST, emailConf.getSmtpHostServer());
	props.put(EmailConstants.SMTPPORT, emailConf.getSmtpPort());
	props.put("mail.smtp.auth", emailConf.getIsAuthRequired());
	props.put("mail.smtp.starttls.enable", emailConf.getSmtpStarttlsEnable());

	// Create a Session object to represent a mail session with the specified
	// properties.
	Session session = Session.getDefaultInstance(props);
	MimeMessage msg = new MimeMessage(session);
	msg.addHeader(EmailConstants.CONTENTTYPE, EmailConstants.CHARSET);
	msg.addHeader(EmailConstants.FORMAT, EmailConstants.FLOWED);
	msg.addHeader(EmailConstants.ENCODING, EmailConstants.BIT);
	msg.setFrom(new InternetAddress(mail.getMailFrom(), EmailConstants.NOREPLY));
	msg.setReplyTo(InternetAddress.parse(mail.getMailTo(), false));
	msg.setSubject(mail.getSubject(), EmailConstants.UTF);
	msg.setSentDate(new Date());
	msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail.getMailTo(), false));
	MimeBodyPart contentPart = new MimeBodyPart();
	contentPart.setContent(emailBody, EmailConstants.HTML);

	Multipart multipart = new MimeMultipart();
	multipart.addBodyPart(contentPart);

	String imageId="logoImage";
	String imagePath="/img/Insights.jpg";
	MimeBodyPart imagePart = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart);

	imageId="footerImage";
	imagePath="/img/FooterImg.jpg";
	MimeBodyPart imagePart_1 = generateContentId(imageId, imagePath);
	multipart.addBodyPart(imagePart_1);

	msg.setContent(multipart);

	try (Transport transport = session.getTransport();) {
		LOG.debug("Sending email...");

		transport.connect(emailConf.getSmtpHostServer(), emailConf.getSmtpUserName(),emailConf.getSmtpPassword());

		// Send the email.
		transport.sendMessage(msg, msg.getAllRecipients());
		LOG.debug("Email sent!");
	} catch (Exception ex) {
		LOG.error("Error sending email",ex);
		throw ex;
	} 

}
 
Example 13
Source File: EmailSenderConfiguration.java    From microservices-testing-examples with MIT License 4 votes vote down vote up
public Session getSession() {
  Properties properties = System.getProperties();
  properties.setProperty("mail.smtp.host", host);
  properties.setProperty("mail.smtp.port", port);
  return Session.getDefaultInstance(properties);
}
 
Example 14
Source File: SignAdminAction.java    From Login-System-SSM with MIT License 4 votes vote down vote up
@Override
	protected ModelAndView handle(HttpServletRequest request,
			HttpServletResponse response, Object object, BindException exception)
			throws Exception {
		Admin admin = (Admin) object;  //将数据封装起来
System.out.println("表单提交过来时的数据是:"+admin.toString());

			if (adminService.addAdmin(admin)) {    //调用该方法,将数据持久到数据库中,如果持久化成功,则发送邮件给当前的注册用户
				try {
					String host = "smtp.qq.com"; // 邮件服务器
					String from = "[email protected]"; // 发送邮件的QQ
					String authcode = "fgoobvssrkuibjhe"; // 对于QQ的个人邮箱而言,密码使用的是客户端的授权码,而不是用户的邮箱密码
					Properties props = System.getProperties();
					props.put("mail.smtp.host", host);
					props.setProperty("mail.transport.protocol", "smtp"); // 发送邮件协议名称
					props.put("mail.smtp.auth", "true"); // 开启授权
					props.put("mail.smtp.user", from);
					props.put("mail.smtp.password", authcode);
					props.put("mail.smtp.port", "587"); // smtp邮件服务器的端口号,必须是587,465端口调试时失败
					props.setProperty("mail.smtp.ssl.enable", "true");

					Session session = Session.getDefaultInstance(props,
							new GMailAuthenticator("[email protected]",
									"fgoobvssrkuibjhe"));

					props.put("mail.debug", "true");

					MimeMessage message = new MimeMessage(session);
					Address fromAddress = new InternetAddress(from);
					Address toAddress = new InternetAddress(admin.getEmail());

					message.setFrom(fromAddress);
					message.setRecipient(Message.RecipientType.TO, toAddress);

					message.setSubject("注册成功确认邮件");
					message.setSentDate(new Date());
					//发送的链接包括其写入到数据库中的UUID,也就是链接localhost:8080/Login_Sys/ActivateServlet和UUID的拼接,#连接两个字符串
					//获取UUID
System.out.println(adminService.getUUID(admin));
					message.setContent("<h1>恭喜你注册成功,请点击下面的连接激活账户</h1><h3><a href='http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate.action?code="+adminService.getUUID(admin)+"'>http://localhost:8080/Login_Sys_Spring_SpringMVC_c3p0/Activate</a></h3>","text/html;charset=utf-8");
					Transport transport = session.getTransport();
					transport.connect(host, from, authcode);
					message.saveChanges();
					Transport.send(message);
					transport.close();

				} catch (Exception ex) {
					throw new RuntimeException(ex);
				}

			} 
	    
//封装一个ModelAndView对象,提供转发视图的功能
	    ModelAndView modelAndView = new ModelAndView();
	    modelAndView.addObject("message", "增加管理员成功");
	    modelAndView.setViewName("sign_success");      //成功之后跳转到该界面,采用逻辑视图,必须要配置视图解析器
		return modelAndView;  //该方法一定要返回modelAndView
	}
 
Example 15
Source File: Mail.java    From mobikul-standalone-pos with MIT License 4 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, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(ApplicationConstants.USERNAME_FOR_SMTP, ApplicationConstants.PASSWORD_FOR_SMTP);
                }
            });
            SMTPAuthenticator authentication = new SMTPAuthenticator();
            javax.mail.Message msg = new MimeMessage(Session
                    .getDefaultInstance(props, authentication));
            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
            String protocol = "smtp";
            props.put("mail." + protocol + ".auth", "true");
            Transport t = session.getTransport(protocol);
            try {
                t.connect(ApplicationConstants.HOST_FOR_MAIL, ApplicationConstants.USERNAME_FOR_SMTP, ApplicationConstants.PASSWORD_FOR_SMTP);
                t.sendMessage(msg, msg.getAllRecipients());
            } finally {
                t.close();
            }

            return true;
        } else {
            return false;
        }
    }
 
Example 16
Source File: DefaultMailSender.java    From Mario with Apache License 2.0 4 votes vote down vote up
public DefaultMailSender() {
	props = System.getProperties();
	session = Session.getDefaultInstance(props, null);
	mimeMessage = new MimeMessage(session);
	multipart = new MimeMultipart();
}
 
Example 17
Source File: SendMessage.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void send(SesClient client,
                        String sender,
                        String recipient,
                        String subject,
                        String bodyText,
                        String bodyHTML
) throws AddressException, MessagingException, IOException {

    Session session = Session.getDefaultInstance(new Properties());

    // Create a new MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Add subject, from and to lines.
    message.setSubject(subject, "UTF-8");
    message.setFrom(new InternetAddress(sender));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));

    // Create a multipart/alternative child container.
    MimeMultipart msgBody = new MimeMultipart("alternative");

    // Create a wrapper for the HTML and text parts.
    MimeBodyPart wrap = new MimeBodyPart();

    // Define the text part.
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent(bodyText, "text/plain; charset=UTF-8");

    // Define the HTML part.
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(bodyHTML, "text/html; charset=UTF-8");

    // Add the text and HTML parts to the child container.
    msgBody.addBodyPart(textPart);
    msgBody.addBodyPart(htmlPart);

    // Add the child container to the wrapper object.
    wrap.setContent(msgBody);

    // Create a multipart/mixed parent container.
    MimeMultipart msg = new MimeMultipart("mixed");

    // Add the parent container to the message.
    message.setContent(msg);

    // Add the multipart/alternative part to the message.
    msg.addBodyPart(wrap);

    try {
        System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        message.writeTo(outputStream);

        ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());

        byte[] arr = new byte[buf.remaining()];
        buf.get(arr);

        SdkBytes data = SdkBytes.fromByteArray(arr);

        RawMessage rawMessage = RawMessage.builder()
                .data(data)
                .build();

        SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
                .rawMessage(rawMessage)
                .build();

        client.sendRawEmail(rawEmailRequest);

    } catch (SesException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }


}
 
Example 18
Source File: AttachmentSerializerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testMessageMTOM() throws Exception {
    MessageImpl msg = new MessageImpl();

    Collection<Attachment> atts = new ArrayList<>();
    AttachmentImpl a = new AttachmentImpl("test.xml");

    InputStream is = getClass().getResourceAsStream("my.wav");
    ByteArrayDataSource ds = new ByteArrayDataSource(is, "application/octet-stream");
    a.setDataHandler(new DataHandler(ds));

    atts.add(a);

    msg.setAttachments(atts);

    // Set the SOAP content type
    msg.put(Message.CONTENT_TYPE, "application/soap+xml");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.setContent(OutputStream.class, out);

    AttachmentSerializer serializer = new AttachmentSerializer(msg);

    serializer.writeProlog();

    String ct = (String) msg.get(Message.CONTENT_TYPE);
    assertTrue(ct.indexOf("multipart/related;") == 0);
    assertTrue(ct.indexOf("start=\"<[email protected]>\"") > -1);
    assertTrue(ct.indexOf("start-info=\"application/soap+xml\"") > -1);

    out.write("<soap:Body/>".getBytes());

    serializer.writeAttachments();

    out.flush();
    DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()), ct);
    MimeMultipart mpart = new MimeMultipart(source);
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage inMsg = new MimeMessage(session);
    inMsg.setContent(mpart);

    inMsg.addHeaderLine("Content-Type: " + ct);

    MimeMultipart multipart = (MimeMultipart) inMsg.getContent();

    MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(0);
    assertEquals("application/xop+xml; charset=UTF-8; type=\"application/soap+xml\"",
                 part.getHeader("Content-Type")[0]);
    assertEquals("binary", part.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<[email protected]>", part.getHeader("Content-ID")[0]);

    InputStream in = part.getDataHandler().getInputStream();
    ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
    IOUtils.copy(in, bodyOut);
    out.close();
    in.close();

    assertEquals("<soap:Body/>", bodyOut.toString());

    MimeBodyPart part2 = (MimeBodyPart) multipart.getBodyPart(1);
    assertEquals("application/octet-stream", part2.getHeader("Content-Type")[0]);
    assertEquals("binary", part2.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<test.xml>", part2.getHeader("Content-ID")[0]);

}
 
Example 19
Source File: MimeReader.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGetNext(final JCas jCas) throws IOException, CollectionException {
  final Path path = files.pop();
  final File file = path.toFile();

  final int left = files.size();

  getMonitor()
      .info(
          "Processing {} ({} %)",
          file.getAbsolutePath(), String.format("%.2f", 100 * (total - left) / (double) total));

  try (FileInputStream is = new FileInputStream(file)) {
    final Session s = Session.getDefaultInstance(new Properties());
    final MimeMessageParser parser = new MimeMessageParser(new MimeMessage(s, is));
    parser.parse();
    final MimeMessage message = parser.getMimeMessage();

    final DocumentAnnotation da = UimaSupport.getDocumentAnnotation(jCas);
    da.setTimestamp(calculateBestDate(message, file));
    da.setDocType("email");
    da.setDocumentClassification("O");
    String source = file.getAbsolutePath().substring(rootFolder.length());
    da.setSourceUri(source);
    da.setLanguage("en");

    // Add all headers as metadata, with email prefix
    final Enumeration<Header> allHeaders = message.getAllHeaders();
    while (allHeaders.hasMoreElements()) {
      final Header header = allHeaders.nextElement();
      addMetadata(jCas, "email." + header.getName(), header.getValue());
    }

    addMetadata(jCas, "from", parser.getFrom());
    addMetadata(jCas, "to", parser.getTo());
    addMetadata(jCas, "cc", parser.getCc());
    addMetadata(jCas, "bcc", parser.getBcc());
    addMetadata(jCas, "subject", parser.getSubject());

    // Add fake title
    addMetadata(jCas, "title", parser.getSubject());

    String actualContent = parser.getPlainContent();

    if (actualContent == null) {
      actualContent = "";
    }

    // TODO: At this point we could create a representation of the addresses, etc in the content
    // eg a table of to, from, and etc
    // then annotate them a commsidentifier, date, person.
    // We could also create relations between sender and receiver

    String content = actualContent + "\n\n---\n\n";

    final String headerBlock = createHeaderBlock(content.length(), jCas, parser);
    content = content + headerBlock;

    final Text text = new Text(jCas);
    text.setBegin(0);
    text.setEnd(actualContent.length());
    text.addToIndexes();

    extractContent(new ByteArrayInputStream(content.getBytes()), source, jCas);
  } catch (final Exception e) {
    getMonitor().warn("Discarding message", e);
  }
}
 
Example 20
Source File: IncomingImapMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Constructs {@link IncomingImapMessage} object based on {@link MimeMessage}
 * 
 * @param fileInfo - reference to the {@link FileInfo} object representing the message.
 * @param serviceRegistry - reference to serviceRegistry object.
 * @param message - {@link MimeMessage}
 * @throws MessagingException
 */
public IncomingImapMessage(FileInfo fileInfo, ServiceRegistry serviceRegistry, MimeMessage message) throws MessagingException
{
    super(Session.getDefaultInstance(new Properties()));
    this.wrappedMessage = message; // temporary save it and then destroyed in writeContent() (to avoid memory leak with byte[] MimeMessage.content field)
    this.buildMessage(fileInfo, serviceRegistry);
}