Java Code Examples for javax.mail.internet.MimeMessage#setRecipients()

The following examples show how to use javax.mail.internet.MimeMessage#setRecipients() . 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: Postman.java    From web-budget with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Listen for e-mail requests through CDI events and send the message
 * 
 * @param mailMessage the message to send
 * @throws Exception if any problem occur in the process
 */
public void send(@Observes MailMessage mailMessage) throws Exception {
   
    final MimeMessage message = new MimeMessage(this.mailSession);

    // message header
    message.setFrom(mailMessage.getFrom());
    message.setSubject(mailMessage.getTitle());
    message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
    message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());
    
    // message body
    message.setText(mailMessage.getContent(), "UTF-8", "html");
    message.setSentDate(new Date());

    // send
    Transport.send(message);
}
 
Example 2
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 3
Source File: EMailTestServer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void deliverMultipartMessage(String user, String password, String from, String subject,
                                                                   String contentType, Object body) throws Exception {
    GreenMailUser greenUser = greenMail.setUser(user, password);
    MimeMultipart multiPart = new MimeMultipart();
    MimeBodyPart textPart = new MimeBodyPart();
    multiPart.addBodyPart(textPart);
    textPart.setContent(body, contentType);

    Session session = GreenMailUtil.getSession(server.getServerSetup());
    MimeMessage mimeMessage = new MimeMessage(session);
    mimeMessage.setRecipients(Message.RecipientType.TO, greenUser.getEmail());
    mimeMessage.setFrom(from);
    mimeMessage.setSubject(subject);
    mimeMessage.setContent(multiPart, "multipart/mixed");
    greenUser.deliver(mimeMessage);
}
 
Example 4
Source File: BasicEmailService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected void setRecipients(Map<RecipientType, InternetAddress[]> headerTo, MimeMessage msg)
		throws MessagingException
{
	if (headerTo != null)
	{
		if (msg.getHeader(EmailHeaders.TO) == null && headerTo.containsKey(RecipientType.TO))
		{
			msg.setRecipients(Message.RecipientType.TO, headerTo.get(RecipientType.TO));
		}
		if (msg.getHeader(EmailHeaders.CC) == null && headerTo.containsKey(RecipientType.CC))
		{
			msg.setRecipients(Message.RecipientType.CC, headerTo.get(RecipientType.CC));
		}
		if (headerTo.containsKey(RecipientType.BCC))
		{
			msg.setRecipients(Message.RecipientType.BCC, headerTo.get(RecipientType.BCC));
		}
	}
}
 
Example 5
Source File: EmailService.java    From tomee with Apache License 2.0 5 votes vote down vote up
@POST
public String lowerCase(final String message) {

    try {

        //Create some properties and get the default Session
        final Properties props = new Properties();
        props.put("mail.smtp.host", "your.mailserver.host");
        props.put("mail.debug", "true");

        final Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("MyUsername", "MyPassword");
            }
        });

        //Set this just to see some internal logging
        session.setDebug(true);

        //Create a message
        final MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress("[email protected]"));
        final InternetAddress[] address = {new InternetAddress("[email protected]")};
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject("JavaMail API test");
        msg.setSentDate(new Date());
        msg.setText(message, "UTF-8");


        Transport.send(msg);
    } catch (final MessagingException e) {
        return "Failed to send message: " + e.getMessage();
    }

    return "Sent";
}
 
Example 6
Source File: MailSender.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
	 * 发送邮件
	 * 
	 * @param recipient
	 *            收件人邮箱地址
	 * @param subject
	 *            邮件主题
	 * @param content
	 *            邮件内容
	 * @throws AddressException
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException 
	 */
	public void send(String recipient, String subject, Object content)
			throws AddressException, MessagingException, UnsupportedEncodingException {
		// 创建mime类型邮件
		final MimeMessage message = new MimeMessage(session);
		if(authenticator!=null && authenticator.getUsername().indexOf("@") >0){
			// 设置发信人
			message.setFrom(new InternetAddress(authenticator.getUsername()));
		}
		if(this.fromEmail!=null){
			message.setFrom(new InternetAddress(this.fromEmail));
		}
		// 设置收件人
		String[] toUsers = recipient.split("[\n,;]") ;
		InternetAddress[] internetAddress = new InternetAddress[toUsers.length] ;
		for(int i=0 ; i<toUsers.length ; i++){
			internetAddress[i] = new InternetAddress(toUsers[i]) ;
		}
		message.setRecipients(RecipientType.TO, internetAddress);
		// 设置主题
//		message.setSubject(subject);
		message.setSubject(MimeUtility.encodeText(subject,"UTF-8","B"));
		// 设置邮件内容
		message.setContent(content.toString(), "text/html;charset=utf-8");
		// 发送
		Transport.send(message);
	}
 
Example 7
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;
}
 
Example 8
Source File: Postman.java    From library with Apache License 2.0 5 votes vote down vote up
/**
 * Listen for e-mail requests through CDI events and send the message
 *
 * @param mailMessage the message to send
 * @throws Exception if any problem occur in the process
 */
public void send(@Observes MailMessage mailMessage) throws Exception {

    // create the message
    final MimeMessage message = new MimeMessage(this.mailSession);

    message.setFrom(mailMessage.getFrom());
    message.setSubject(mailMessage.getTitle());
    message.setRecipients(Message.RecipientType.TO, mailMessage.getAddressees());
    message.setRecipients(Message.RecipientType.CC, mailMessage.getCcs());

    message.setSentDate(new Date());

    final MimeMultipart multipart = new MimeMultipart();

    // message text
    final MimeBodyPart messagePart = new MimeBodyPart();

    messagePart.setText(mailMessage.getContent(), "UTF-8", "html");
    multipart.addBodyPart(messagePart);

    // attachments part
    mailMessage.getAttachments().forEach(file -> {
        try {
            final FileDataSource dataSource = new FileDataSource(file);
            final MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(new DataHandler(dataSource));
            attachmentPart.setFileName(dataSource.getName());
            multipart.addBodyPart(attachmentPart);
        } catch (MessagingException ex) {
            throw new BusinessLogicException("error.email.cant-attach-file", ex, file.getName());
        }
    });

    message.setContent(multipart);

    // send
    Transport.send(message);
}
 
Example 9
Source File: MailManager.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Add recipient addresses to the e-mail.
 * @param msg The mime message to which add the addresses.
 * @param recType The specific recipient type to which add the addresses.
 * @param recipients The recipient addresses.
 */
protected void addRecipients(MimeMessage msg, RecipientType recType, String[] recipients) {
	if (null != recipients) {
		try {
			Address[] addresses = new Address[recipients.length];
			for (int i = 0; i < recipients.length; i++) {
				Address address = new InternetAddress(recipients[i]);
				addresses[i] = address;
			}
			msg.setRecipients(recType, addresses);
		} catch (MessagingException e) {
			throw new RuntimeException("Error adding recipients", e);
		}
	}
}
 
Example 10
Source File: SendMail.java    From live-chat-engine with Apache License 2.0 5 votes vote down vote up
public static void main_send_by_concept() {
	
	String fromMail = "";
	String toMail = "";
	String subject = "Тестовый заголовок";
	String text = "<html><body><h1>Тест</h1><p>Тест отправки письма</body></html>";
	String username = "";
	String password = "";

	Properties props = new Properties();
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.host", "smtp.gmail.com");
	props.put("mail.smtp.port", "587");
	
	Session session = Session.getInstance(props,
	  new javax.mail.Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);
		}
	  });

	try {

		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(fromMail));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
		message.setSubject(subject);
		message.setText(text, "UTF-8", "html");

		Transport.send(message);

	} catch (MessagingException e) {
		throw new RuntimeException(e);
	}
	
}
 
Example 11
Source File: MailSession.java    From gocd with Apache License 2.0 5 votes vote down vote up
public MimeMessage createMessage(String from, String to, String subject, String body)
        throws MessagingException {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(TO, to);
    msg.setSubject(subject);
    msg.setContent(msg, "text/plain");
    msg.setSentDate(new Date());
    msg.setText(body);
    msg.setSender(new InternetAddress(from));
    msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)});
    return msg;
}
 
Example 12
Source File: Mails.java    From jease with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sends an email synchronously.
 */
public static void send(String sender, String recipients, String subject,
		String text) throws MessagingException {
	final Properties properties = Database.query(propertySupplier);
	if (properties != null) {
		Session session = Session.getInstance(properties,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(properties
								.getProperty("mail.smtp.user", ""),
								properties.getProperty(
										"mail.smtp.password", ""));
					}
				});
		MimeMessage message = new MimeMessage(session);
		message.setFrom(new InternetAddress(sender));
		message.setReplyTo(new InternetAddress[] { new InternetAddress(
				sender) });
		message.setRecipients(Message.RecipientType.TO, recipients);
		message.setSubject(subject, "utf-8");
		message.setSentDate(new Date());
		message.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
		message.setHeader("Content-Transfer-Encoding", "quoted-printable");
		message.setText(text, "utf-8");
		Transport.send(message);
	}
}
 
Example 13
Source File: EmailUtils.java    From CodeDefenders with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sends an email to a given recipient for a given subject and content
 * with a {@code reply-to} header.
 *
 * @param to      The recipient of the mail ({@code to} header).
 * @param subject The subject of the mail.
 * @param text    The content of the mail.
 * @param replyTo The {@code reply-to} email header.
 * @return {@code true} if successful, {@code false} otherwise.
 */
private static boolean sendEmail(String to, String subject, String text, String replyTo) {
    final boolean emailEnabled = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAILS_ENABLED).getBoolValue();
    if (!emailEnabled) {
        logger.error("Tried to send a mail, but sending emails is disabled. Update your system settings.");
        return false;
    }

    final String smtpHost = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_HOST).getStringValue();
    final int smtpPort = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_PORT).getIntValue();
    final String emailAddress = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_ADDRESS).getStringValue();
    final String emailPassword = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_PASSWORD).getStringValue();
    final boolean debug = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.DEBUG_MODE).getBoolValue();

    try    {
        Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);

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

        session.setDebug(debug);
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(emailAddress));
        msg.setReplyTo(InternetAddress.parse(replyTo));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        msg.setSubject(subject);
        msg.setContent(text, "text/plain");
        msg.setSentDate(new Date());

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpHost, smtpPort, emailAddress, emailPassword);
        Transport.send(msg);
        transport.close();

        logger.info(String.format("Mail sent: to: %s, replyTo: %s", to, replyTo));
    } catch (MessagingException messagingException) {
        logger.warn("Failed to send email.", messagingException);
        return false;
    }
    return true;
}
 
Example 14
Source File: MailDaemon.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * sends invitation
 * 
 * @param session     session connection to the SMTP server
 * @param toemails    list of recipient e-mails
 * @param subject     invitation subject
 * @param body        invitation start
 * @param fromemail   user sending the invitation
 * @param startdate   start date of the invitation
 * @param enddate     end date of the invitation
 * @param location    location of the invitation
 * @param uid         unique id
 * @param cancelation true if this is a cancelation
 */
private void sendInvitation(Session session, String[] toemails, String subject, String body, String fromemail,
		Date startdate, Date enddate, String location, String uid, boolean cancelation) {
	try {
		// prepare mail mime message
		MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap();
		mimetypes.addMimeTypes("text/calendar ics ICS");
		// register the handling of text/calendar mime type
		MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
		mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");

		MimeMessage msg = new MimeMessage(session);
		// set message headers

		msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
		msg.addHeader("format", "flowed");
		msg.addHeader("Content-Transfer-Encoding", "8bit");
		InternetAddress fromemailaddress = new InternetAddress(fromemail);
		msg.setFrom(fromemailaddress);
		msg.setReplyTo(InternetAddress.parse(fromemail, false));
		msg.setSubject(subject, "UTF-8");
		msg.setSentDate(new Date());

		// set recipient

		InternetAddress[] recipients = new InternetAddress[toemails.length + 1];

		String attendeesinvcalendar = "";
		for (int i = 0; i < toemails.length; i++) {
			recipients[i] = new InternetAddress(toemails[i]);
			attendeesinvcalendar += "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"
					+ toemails[i] + "\n";
		}

		recipients[toemails.length] = fromemailaddress;
		msg.setRecipients(Message.RecipientType.TO, recipients);

		Multipart multipart = new MimeMultipart("alternative");
		// set body
		MimeBodyPart descriptionPart = new MimeBodyPart();
		descriptionPart.setContent(body, "text/html; charset=utf-8");
		multipart.addBodyPart(descriptionPart);

		// set invitation
		BodyPart calendarPart = new MimeBodyPart();

		String method = "METHOD:REQUEST\n";
		if (cancelation)
			method = "METHOD:CANCEL\n";

		String calendarContent = "BEGIN:VCALENDAR\n" + method + "PRODID: BCP - Meeting\n" + "VERSION:2.0\n"
				+ "BEGIN:VEVENT\n" + "DTSTAMP:" + iCalendarDateFormat.format(new Date()) + "\n" + "DTSTART:"
				+ iCalendarDateFormat.format(startdate) + "\n" + "DTEND:" + iCalendarDateFormat.format(enddate)
				+ "\n" + "SUMMARY:" + subject + "\n" + "UID:" + uid + "\n" + attendeesinvcalendar
				+ "ORGANIZER:MAILTO:" + fromemail + "\n" + "LOCATION:" + location + "\n" + "DESCRIPTION:" + subject
				+ "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n"
				+ "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n"
				+ "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR";

		calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
		calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");
		multipart.addBodyPart(calendarPart);
		msg.setContent(multipart);
		logger.severe("Invitation is ready");
		Transport.send(msg);

		logger.severe("EMail Invitation Sent Successfully!! to " + attendeesinvcalendar);
	} catch (Exception e) {
		logger.severe(
				"--- Exception in sending invitation --- " + e.getClass().toString() + " - " + e.getMessage());
		if (e.getCause() != null)
			logger.severe(" cause  " + e.getCause().getClass().toString() + " - " + e.getCause().getMessage());
		throw new RuntimeException("email sending error " + e.getMessage() + " for server = server:"
				+ this.smtpserver + " - port:" + this.port + " - user:" + this.user);
	}

}
 
Example 15
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 16
Source File: EmailLogServlet.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public boolean sendLog(String host, String userId, String password,
        String to, String from, String subject, String message,
        File filename) {
    boolean success = true;
    System.out.println("host: " + host);
    System.out.println("userId: " + userId);
    // Fortify Mod: commented out clear text password.
    // System.out.println("password: " + password);
    System.out.println("to: " + to);
    System.out.println("from: " + from);
    System.out.println("subject: " + subject);
    System.out.println("message: " + message);
    System.out.println("filename: " + filename.getName());
    System.out.println("filename: " + filename.getAbsolutePath());

    // create some properties and get the default Session
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.auth", "true");

    Session session = Session.getInstance(props, null);
    session.setDebug(true);

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        msg.setRecipients(Message.RecipientType.TO, address);
        msg.setSubject(subject);

        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setText(message);

        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(filename);
        mbp2.setDataHandler(new DataHandler(fds));
        mbp2.setFileName(fds.getName());

        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);

        // add the Multipart to the message
        msg.setContent(mp);

        // set the Date: header
        msg.setSentDate(new Date());

        // connect to the transport
        Transport trans = session.getTransport("smtp");
        trans.connect(host, userId, password);

        // send the message
        trans.sendMessage(msg, msg.getAllRecipients());

        // smtphost
        trans.close();

    } catch (MessagingException mex) {
        success = false;
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
    return success;
}
 
Example 17
Source File: SendMail.java    From OA with GNU General Public License v3.0 4 votes vote down vote up
public boolean send() {
		// 创建邮件Session所需的Properties对象.API建议使用set而不是put(putall).
		Properties props = new Properties();
		props.setProperty("mail.smtp.host", smtpServer);
		props.setProperty("mail.smtp.auth", "true");
		props.put("mail.smtp.ssl.enable", "false");
		props.put("mail.debug", "true");
		// 创建Session对象,代表JavaMail中的一次邮件会话.
		// Authenticator==>Java mail的身份验证,如QQ邮箱是需要验证的.所以需要用户名,密码.
		// PasswordAuthentication==>系统的密码验证.内部类获取,或者干脆写个静态类也可以.
		Session session = Session.getDefaultInstance(props,
				new Authenticator() {
					public PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(userName, password);
					}
				});

		try {
			// 构造MimeMessage并设置相关属性值,MimeMessage就是实际的电子邮件对象.
			MimeMessage msg = new MimeMessage(session);
			// 设置发件人
			msg.setFrom(new InternetAddress(from));
			// 设置收件人,为数组,可输入多个地址.
			InternetAddress[] addresses = { new InternetAddress(to) };
			// Message.RecipientType==>TO(主要接收人),CC(抄送),BCC(密件抄送)
			msg.setRecipients(Message.RecipientType.TO, addresses);
			msg.setSentDate(new Date());
			// 设置邮件主题,如果不是UTF-8就要转换下.MimeUtility.encodeText(subject,"gb2312","B"));
//			 subject=translateChinese(subject);
			msg.setSubject(MimeUtility.encodeText(subject,"utf8","B"));
			// =====================正文部分===========
			// 构造Multipart容器
			Multipart mp = new MimeMultipart();
			// =====================正文文字部分===========
			// 向Multipart添加正文
			MimeBodyPart mbpContent = new MimeBodyPart();
			
			mbpContent.setContent(content,"text/plain;charset=gb2312");
			// 将BodyPart添加到MultiPart容器中
			mp.addBodyPart(mbpContent);

			// =====================正文附件部分===========
			// 向MulitPart添加附件,遍历附件列表,将所有文件添加到邮件消息里
			if (attachments != null) {
				for (String efile : attachments) {
					MimeBodyPart mbpFile = new MimeBodyPart();
					// 以文件名创建FileDataSource对象
					FileDataSource fds = new FileDataSource(efile);
					// 处理附件
					mbpFile.setDataHandler(new DataHandler(fds));
					mbpFile.setFileName(fds.getName());
					// 将BodyPart添加到Multipart容器中
					mp.addBodyPart(mbpFile);
				}
				attachments.clear();
			}
			
			// 向MimeMessage添加Multipart
			msg.setContent(mp);
			msg.setSentDate(new Date());
			// 发送邮件,使用如下方法!
			Transport.send(msg);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
 
Example 18
Source File: SesSendNotificationHandler.java    From smart-security-camera with GNU General Public License v3.0 4 votes vote down vote up
public Parameters handleRequest(Parameters parameters, Context context) {
	context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	try {
		Session session = Session.getDefaultInstance(new Properties());
		MimeMessage message = new MimeMessage(session);
		message.setSubject(EMAIL_SUBJECT, "UTF-8");
		message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM")));
		message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) });
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(System.getenv("EMAIL_RECIPIENT")));

		MimeBodyPart wrap = new MimeBodyPart();
		MimeMultipart cover = new MimeMultipart("alternative");
		MimeBodyPart html = new MimeBodyPart();
		cover.addBodyPart(html);
		wrap.setContent(cover);
		MimeMultipart content = new MimeMultipart("related");
		message.setContent(content);
		content.addBodyPart(wrap);

		URL attachmentURL = new URL(
				System.getenv("S3_URL_PREFIX") + parameters.getS3Bucket() + '/' + parameters.getS3Key());

		StringBuilder sb = new StringBuilder();
		String id = UUID.randomUUID().toString();
		sb.append("<img src=\"cid:");
		sb.append(id);
		sb.append("\" alt=\"ATTACHMENT\"/>\n");

		MimeBodyPart attachment = new MimeBodyPart();
		DataSource fds = new URLDataSource(attachmentURL);
		attachment.setDataHandler(new DataHandler(fds));

		attachment.setContentID("<" + id + ">");
		attachment.setDisposition("attachment");

		attachment.setFileName(fds.getName());
		content.addBodyPart(attachment);

		String prettyPrintLabels = parameters.getRekognitionLabels().toString();
		prettyPrintLabels = prettyPrintLabels.replace("{", "").replace("}", "");
		prettyPrintLabels = prettyPrintLabels.replace(",", "<br>");
		html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/", "")
				+ "</h2><p><i>Step Function ID : " + parameters.getStepFunctionID()
				+ "</i></p><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>" + sb
				+ "</body></html>", "text/html");

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		message.writeTo(outputStream);
		RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
		SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);

		AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient();
		client.sendRawEmail(rawEmailRequest);

	// Convert Checked Exceptions to RuntimeExceptions to ensure that
	// they get picked up by the Step Function infrastructure
	} catch (MessagingException | IOException e) {
		throw new RuntimeException("Error in [" + context.getFunctionName() + "]", e);
	}

	context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	return parameters;
}
 
Example 19
Source File: SendMessage.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void send() 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(BODY_TEXT, "text/plain; charset=UTF-8");

        // Define the HTML part
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(BODY_HTML, "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...");

            Region region = Region.US_WEST_2;

            SesClient client = SesClient.builder().region(region).build();

            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 (SdkException e) {
            e.getStackTrace();
        }
        // snippet-end:[ses.java2.sendmessage.main]
    }
 
Example 20
Source File: SenderImpl.java    From live-chat-engine with Apache License 2.0 4 votes vote down vote up
@Override
public void send(SendTask task, Props props) throws Exception {
	
	Properties sessionProps = new Properties();
	sessionProps.put("mail.smtp.auth", props.getStrVal(mail_smtp_auth));
	sessionProps.put("mail.smtp.starttls.enable", props.getStrVal(mail_smtp_starttls_enable));
	sessionProps.put("mail.smtp.host", props.getStrVal(mail_smtp_host));
	sessionProps.put("mail.smtp.port", props.getStrVal(mail_smtp_port));
	sessionProps.put("mail.debug", props.getStrVal(mail_debug));
	
	if(props.getBoolVal(mail_skipSslCertCheck)){
		sessionProps.put("mail.smtp.ssl.checkserveridentity", "false");
		sessionProps.put("mail.smtp.ssl.trust", "*");
	}

	Session session = Session.getInstance(sessionProps, new Authenticator() {

		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(props.getStrVal(mail_username), props.getStrVal(mail_password));
		}
		
	});
	
	MailMsg msg = task.msg;

	MimeMessage message = new MimeMessage(session);
	message.setFrom(msg.fromEmail);
	message.setSubject(msg.subject);
	message.setText(msg.text, msg.charset, msg.subtype);
	
	Map<RecipientType, List<InternetAddress>> recipients = task.recipientGroup.byType();
	for (Entry<RecipientType, List<InternetAddress>> entry : recipients.entrySet()) {
		message.setRecipients(entry.getKey(), array(entry.getValue(), Address.class));
	}		
	
	if( ! isEmpty(msg.replyTo)){
		message.setReplyTo(array(msg.replyTo, Address.class));
	}

	Transport.send(message);

}