Java Code Examples for javax.mail.Message

The following are top voted examples for showing how to use javax.mail.Message. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: web-framework-for-java   File: MailHelper.java   Source Code and License 12 votes vote down vote up
public static void sendMail(String host, int port, String username, String password, String recipients,
		String subject, String content, String from) throws AddressException, MessagingException {
	
	Properties props = new Properties();
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.host", host);
	props.put("mail.smtp.port", port);

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

	Message message = new MimeMessage(session);
	message.setFrom(new InternetAddress(from));
	message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
	message.setSubject(subject);
	message.setText(content);

	Transport.send(message);
}
 
Example 2
Project: oscm   File: MailReader.java   Source Code and License 11 votes vote down vote up
/**
 * Get the content of a mail message.
 * 
 * @param message
 *            the mail message
 * @return the content of the mail message
 */
private String getMessageContent(Message message) throws MessagingException {
    try {
        Object content = message.getContent();
        if (content instanceof Multipart) {
            StringBuffer messageContent = new StringBuffer();
            Multipart multipart = (Multipart) content;
            for (int i = 0; i < multipart.getCount(); i++) {
                Part part = multipart.getBodyPart(i);
                if (part.isMimeType("text/plain")) {
                    messageContent.append(part.getContent().toString());
                }
            }
            return messageContent.toString();
        }
        return content.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 3
Project: AndroidKillerService   File: SimpleMailSender.java   Source Code and License 8 votes vote down vote up
public boolean sendTextMail(MailSenderInfo mailInfo) {
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());
        mailMessage.setText(mailInfo.getContent());
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
 
Example 4
Project: AndroidKillerService   File: SimpleMailSender.java   Source Code and License 7 votes vote down vote up
public boolean sendAttachMail(MailSenderInfo mailInfo) {
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());
        Multipart multi = new MimeMultipart();
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        multi.addBodyPart(textBodyPart);
        for (String path : mailInfo.getAttachFileNames()) {
            DataSource fds = new FileDataSource(path);
            BodyPart fileBodyPart = new MimeBodyPart();
            fileBodyPart.setDataHandler(new DataHandler(fds));
            fileBodyPart.setFileName(path.substring(path.lastIndexOf("/") + 1));
            multi.addBodyPart(fileBodyPart);
        }
        mailMessage.setContent(multi);
        mailMessage.saveChanges();
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
 
Example 5
Project: oscm   File: Transport.java   Source Code and License 7 votes vote down vote up
@Override
public void sendMessage(Message msg, Address[] addresses)
        throws MessagingException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        msg.writeTo(out);
        lastMail = new String(out.toByteArray(), "UTF-8");
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 6
Project: rapidminer   File: MailSenderSMTP.java   Source Code and License 6 votes vote down vote up
@Override
public void sendEmail(String address, String subject, String content, Map<String, String> headers) throws Exception {
	Session session = MailUtilities.makeSession();
	if (session == null) {
		// LogService.getRoot().warning("Unable to create mail session. Not sending mail to "+address+".");
		LogService.getRoot().log(Level.WARNING, "com.rapidminer.tools.MailSenderSMTP.creating_mail_session_error",
				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 7
Project: Mastering-Java-EE-Development-with-WildFly   File: SendMailWithResource.java   Source Code and License 6 votes vote down vote up
public void send(String addresses, String topic, String textMessage) {

		try {
			session.getProperties().put("mail.smtp.port", 25000);
			Message message = new MimeMessage(session);
			message.setRecipients(TO, InternetAddress.parse(addresses));
			message.setSubject(topic);
			message.setText(textMessage);

			Transport.send(message);
			logger.info("sent mail with resource!");

		} catch (MessagingException e) {
			logger.log(WARNING, "Cannot send mail", e);
		}
	}
 
Example 8
Project: trading4j   File: MailSender.java   Source Code and License 6 votes vote down vote up
/**
 * Sends an email.
 * 
 * @param from
 *            The Email-address from the sender of this mail.
 * @param to
 *            The Email-address of the receiver of this mail.
 * @param subject
 *            The subject of the mail.
 * @param body
 *            The content of the mail.
 * @throws MailSendingException
 *             When sending the mail failed.
 */
public void sendMail(final String from, final String to, final String subject, final String body)
        throws MailSendingException {
    final MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSentDate(new Date());
        message.setSubject(subject);
        message.setText(body);

        Transport.send(message);
    } catch (final MessagingException e) {
        throw new MailSendingException("Sending an email failed.", e);
    }

}
 
Example 9
Project: AndroidKillerService   File: SimpleMailSender.java   Source Code and License 6 votes vote down vote up
public boolean sendHtmlMail(MailSenderInfo mailInfo) {
    XLog.d("发送网页版邮件!");
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        String[] receivers = mailInfo.getReceivers();
        Address[] tos = new InternetAddress[receivers.length];
        for (int i = 0; i < receivers.length; i++) {
            tos[i] = new InternetAddress(receivers[i]);
        }
        mailMessage.setRecipients(Message.RecipientType.TO, tos);
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());

        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
 
Example 10
Project: Java-9-Programming-Blueprints   File: Rule.java   Source Code and License 6 votes vote down vote up
private SearchTerm createFieldSearchTerm(String f) {
    switch (f.toLowerCase()) {
        case "from":
            return new FromStringTerm(matchingText);
        case "cc":
            return new RecipientStringTerm(Message.RecipientType.CC, matchingText);
        case "to":
            return new RecipientStringTerm(Message.RecipientType.TO, matchingText);
        case "body":
            return new BodyTerm(matchingText);
        case "subject":
            return new SubjectTerm(matchingText);
        default:
            return null;
    }
}
 
Example 11
Project: redesocial   File: Enviar_email.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
      Properties props = new Properties();
      /** Parâmetros de conexão com servidor Gmail */
      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() {
                       protected PasswordAuthentication getPasswordAuthentication() 
                       {
                             return new PasswordAuthentication("[email protected]", "tjm123456");
                       }
                  });
      /** Ativa Debug para sessão */
      session.setDebug(true);
      try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]")); //Remetente

            Address[] toUser = InternetAddress //Destinatário(s)
                       .parse("[email protected]");  
            message.setRecipients(Message.RecipientType.TO, toUser);
            message.setSubject("Enviando email com JavaMail");//Assunto
            message.setText("Enviei este email utilizando JavaMail com minha conta GMail!");
            /**Método para enviar a mensagem criada*/
            Transport.send(message);
            System.out.println("Feito!!!");
       } catch (MessagingException e) {
            throw new RuntimeException(e);
      }
}
 
Example 12
Project: plugin-password   File: PasswordResource.java   Source Code and License 6 votes vote down vote up
private void prepareAndSendMail(final SimpleUserOrg user, final String password) {
	sendMail(mimeMessage -> {
		final String fullName = user.getFirstName() + " " + user.getLastName();
		final InternetAddress[] internetAddresses = getUserInternetAdresses(user, fullName);
		final String link = "<a href=\"" + configurationResource.get(URL_PUBLIC) + "\">"
				+ configurationResource.get(URL_PUBLIC) + "</a>";
		mimeMessage.setHeader("Content-Type", "text/plain; charset=UTF-8");
		mimeMessage.setFrom(new InternetAddress(configurationResource.get(MESSAGE_FROM),
				configurationResource.get(MESSAGE_FROM_TITLE), StandardCharsets.UTF_8.name()));
		mimeMessage.setSubject(String.format(configurationResource.get(MESSAGE_NEW_SUBJECT), fullName),
				StandardCharsets.UTF_8.name());
		mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses);
		mimeMessage.setContent(String.format(configurationResource.get(MESSAGE_NEW), fullName, user.getId(),
				password, link, fullName, user.getId(), password, link), "text/html; charset=UTF-8");
	});
}
 
Example 13
Project: webpage-update-subscribe   File: EmailServer.java   Source Code and License 6 votes vote down vote up
private Message buildEmailMessage(EmailInfo emailInfo)
		throws AddressException, MessagingException, UnsupportedEncodingException {
	MimeMessage message = new MimeMessage(this.session);
	message.setFrom(new InternetAddress(emailInfo.getFrom(), "网页更新订阅系统", "UTF-8"));
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailInfo.getTo()));

	Multipart multipart = new MimeMultipart();
	BodyPart messageBodyPart = new MimeBodyPart();
	messageBodyPart.setContent(emailInfo.getContent(), "text/html;charset=UTF-8");
	multipart.addBodyPart(messageBodyPart);
	message.setContent(multipart);
	message.setSubject(emailInfo.getTitle());
	message.saveChanges();
	return message;
}
 
Example 14
Project: spring-rest-skeleton   File: LoggableMailSender.java   Source Code and License 6 votes vote down vote up
/**
 * Extracts string data from {@link MimeMessage}.
 *
 * @param mimeMessage
 * @return
 */
public static String getStringInfo(MimeMessage mimeMessage) {
	StringBuilder sb = new StringBuilder("MimeMessage: ");
	try {
		sb.append("from=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getFrom())).append("; ");
		sb.append("replyTo=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getReplyTo())).append("; ");
		sb.append("to=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.TO))).append("; ");
		sb.append("cc=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.CC))).append("; ");
		sb.append("bcc=").append(StringUtils.arrayToCommaDelimitedString(mimeMessage.getRecipients(Message.RecipientType.BCC))).append("; ");
		sb.append("subject=").append(mimeMessage.getSubject());
	} catch (MessagingException e) {
		LOG.error("Error retrieving log message: {}", e.getMessage());
	}

	return sb.toString();
}
 
Example 15
Project: ats-framework   File: Test_MailReportSender.java   Source Code and License 6 votes vote down vote up
@Test
public void sendReport() throws MessagingException {

    mockStatic(Transport.class);

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

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

    replayAll();

    triggerRun();

    verifyAll();
}
 
Example 16
Project: Spring-web-shop-project   File: SendEmailUserAccount.java   Source Code and License 6 votes vote down vote up
public static void sendEmailWithOrder(String text, String eMail, HttpServletRequest request) {
    try {
        Session session = EmailActions.authorizeWebShopEmail();

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(ApplicationProperties.SHOP_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMail, false));
        msg.setSubject("Shop order");
        msg.setText(text);
        msg.setSentDate(new Date());
        Transport.send(msg);
    } catch (MessagingException e) {
        System.out.println("Error : " + e);
    }
}
 
Example 17
Project: Blockchain-Academic-Verification-Service   File: EmailService.java   Source Code and License 6 votes vote down vote up
@Override
public boolean sendToAdmin(final String institutionEmailAddress, final String applicationMessage) {
    String[] to = new String[]{"[email protected]"};
    setupProperties();
    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(username));
        InternetAddress[] toAddress = new InternetAddress[to.length];

        // To get the array of addresses
        for (int i = 0; i < to.length; i++) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for (int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }
        message.setSubject(APPLICATION_SUBJECT);
        message.setText(applicationBody + "Email: " + institutionEmailAddress + "\nMessage: " + applicationMessage);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        LOGGER.info("Email sent to Admin");
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 18
Project: Cognizant-Intelligent-Test-Scripter   File: Mailer.java   Source Code and License 6 votes vote down vote up
private static void sendMail()
        throws MessagingException, IOException {
    Session session = Session.getInstance(getMailProps(), new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    getVal("username"),
                    getVal("password"));
        }
    });
    session.setDebug(getBoolVal("mail.debug"));
    LOG.info("Compiling Mail before Sending");
    Message message = createMessage(session);
    Transport transport = session.getTransport("smtp");
    LOG.info("Connecting to Mail Server");
    transport.connect();
    LOG.info("Sending Mail");
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    LOG.info("Reports are sent to Mail");
    clearTempZips();
}
 
Example 19
Project: jsf-core   File: ReciveMail.java   Source Code and License 6 votes vote down vote up
/**  
 * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】  
 */  
public boolean isNew() throws MessagingException {   
    boolean isnew = false;   
    Flags flags = ((Message) mimeMessage).getFlags();   
    Flags.Flag[] flag = flags.getSystemFlags();   
    logger.info("flags's length: " + flag.length);   
    for (int i = 0; i < flag.length; i++) {   
        if (flag[i] == Flags.Flag.SEEN) {   
            isnew = true;   
            logger.info("seen Message.......");   
            break;   
        }   
    }   
    return isnew;   
}
 
Example 20
Project: Spring-web-shop-project   File: SendEmailDeleteAccount.java   Source Code and License 6 votes vote down vote up
public static String sendCode(User user, HttpServletRequest request) {
    try {
        Session session = EmailActions.authorizeWebShopEmail();

        String code = Long.toHexString(Double.doubleToLongBits(Math.random()));
        request.getSession().setAttribute("deleteAccountCode", code);
        request.getSession().setAttribute("userName", user.getLogin());
        System.out.println(code);

        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(ApplicationProperties.SHOP_EMAIL));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.geteMail(), false));
        msg.setSubject("Delete account");
        msg.setText("Link : " + ApplicationProperties.URL + ApplicationProperties.PROJECT_NAME + "account/deleteAccountCode/" + code);
        msg.setSentDate(new Date());
        Transport.send(msg);

    } catch (MessagingException e) {
        System.out.println("Error : " + e);
    }
    return "loginAndRegistration/reset/codePassword";
}
 
Example 21
Project: HueSense   File: MailService.java   Source Code and License 6 votes vote down vote up
private void sendMail(String subject, String body, MailSettings settings) throws MessagingException {

        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", settings.getSmtpServer());
        props.put("mail.smtp.port", settings.getSmtpPort() + "");

        if (settings.getMode() == MailSettings.Mode.SSL) {
            props.put("mail.smtp.socketFactory.port", settings.getSmtpPort() + "");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
        } else if (settings.getMode() == MailSettings.Mode.TLS) {
            props.put("mail.smtp.starttls.enable", "true");
        }

        props.put("mail.smtp.auth", settings.isUseAuth() + "");

        Session session;
        if (settings.isUseAuth()) {
            session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getUser(), settings.getPass());
                }
            });
        } else {
            session = Session.getInstance(props);
        }

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settings.getFrom()));
        message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(settings.getTo()));
        message.setSubject(subject);
        message.setText(body);

        Transport.send(message);

    }
 
Example 22
Project: Log4Reports   File: EmailUtil.java   Source Code and License 6 votes vote down vote up
public static void sendMail(String subject, String content, String receivers, String path){
  	recipients = receivers;
  	new EmailUtil();
      Message message;
try {
	String suffix = new File(path).getName();
	if(suffix.endsWith(".jpg") || suffix.endsWith(".png") || suffix.endsWith(".gif")){
		message = createImageMail(subject, content, path);
	}else{
		message = createAttachMail(subject, content, path);
	}
	
	ts.sendMessage(message, message.getAllRecipients());
       ts.close();
       System.out.println("send email finished.");
} catch (Exception e) {
	System.err.println("send email failed.");
	e.printStackTrace();
}      
  }
 
Example 23
Project: Log4Reports   File: EmailUtil.java   Source Code and License 5 votes vote down vote up
/**
  * @Method: createImageMail
  * @Description: ����һ���ʼ����Ĵ�ͼƬ���ʼ�
  * @param session
  * @return
  * @throws Exception
  */ 
  public static MimeMessage createImageMail(String subject, String content, String imagePath) throws Exception {

      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(username));
      if(recipients.contains(";")){
	List<InternetAddress> list = new ArrayList<InternetAddress>();
	String []median=recipients.split(";");
	for(int i=0;i<median.length;i++){
		list.add(new InternetAddress(median[i]));
	}
	InternetAddress[] address =list.toArray(new InternetAddress[list.size()]);
	message.setRecipients(Message.RecipientType.TO,address);
}else{
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
}
      message.setSubject(subject);
      MimeBodyPart text = new MimeBodyPart();
      text.setContent(content, "text/html;charset=UTF-8");
      MimeBodyPart image = new MimeBodyPart();
      DataHandler dh = new DataHandler(new FileDataSource(imagePath));
      image.setDataHandler(dh);
      image.setContentID("xxx.jpg");
      MimeMultipart mm = new MimeMultipart();
      mm.addBodyPart(text);
      mm.addBodyPart(image);
      mm.setSubType("related");

      message.setContent(mm);
      message.saveChanges();
      return message;
  }
 
Example 24
Project: iBase4J-Common   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置收信人
 * 
 * @param to
 * @return
 */
public boolean setTo(String to) {
	if (to == null)
		return false;
	logger.info(Resources.getMessage("EMAIL.SET_TO"), to);
	try {
		mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		return true;
	} catch (Exception e) {
		logger.error(e.getLocalizedMessage());
		return false;
	}
}
 
Example 25
Project: iBase4J-Common   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置抄送人
 * @param copyto
 * @return
 */
public boolean setCopyTo(String copyto) {
	if (copyto == null)
		return false;
	logger.info(Resources.getMessage("EMAIL.SET_COPYTO"), copyto);
	try {
		mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto));
		return true;
	} catch (Exception e) {
		return false;
	}
}
 
Example 26
Project: fakesmtp-junit-runner   File: MailSender.java   Source Code and License 5 votes vote down vote up
/**
 * Send mail.
 *
 * @param from
 *            Sender's email ID needs to be mentioned
 * @param to
 *            Recipient's email ID needs to be mentioned.
 * @param subject
 *            the subject
 * @throws MessagingException
 */
public void sendMail(String from, String to, String subject, String body) throws MessagingException {

	// Get system properties
	Properties properties = System.getProperties();

	// Setup mail server
	properties.setProperty("mail.smtp.host", host);
	properties.setProperty("mail.smtp.port", Integer.toString(port));

	// Get the default Session object.
	Session session = Session.getDefaultInstance(properties);

	Transport transport = null;
	try {
		transport = session.getTransport();

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

		// Set From: header field of the header.
		message.setFrom(new InternetAddress(from));

		// Set To: header field of the header.
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

		// Set Subject: header field
		message.setSubject(subject);

		// Now set the actual message
		message.setText(body);

		// Send message
		transport.send(message);
		System.out.println("Sent message successfully....");
	} finally {
		if (transport != null) {
			transport.close();
		}
	}

}
 
Example 27
Project: JAVA-   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 发送邮件
 * 
 * @param name String
 * @param pass String
 */
public boolean sendout() {
	try {
		mimeMsg.setContent(mp);
		mimeMsg.saveChanges();

		logger.info(Resources.getMessage("EMAIL.SENDING"));
		Session mailSession = Session.getInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				if (userkey == null || "".equals(userkey.trim())) {
					return null;
				}
				return new PasswordAuthentication(username, userkey);
			}
		});
		Transport transport = mailSession.getTransport("smtp");
		transport.connect((String) props.get("mail.smtp.host"), username, password);
		// 设置发送日期
		mimeMsg.setSentDate(new Date());
		// 发送
		transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
		if (mimeMsg.getRecipients(Message.RecipientType.CC) != null) {
			transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
		}
		logger.info(Resources.getMessage("EMAIL.SEND_SUCC"));
		transport.close();
		return true;
	} catch (Exception e) {
		logger.error(Resources.getMessage("EMAIL.SEND_ERR"), e);
		return false;
	}
}
 
Example 28
Project: Java-9-Programming-Blueprints   File: AccountProcessor.java   Source Code and License 5 votes vote down vote up
private void moveMessage(Message toMove, Folder dest) {
    if (toMove != null) {
        try {
            final Folder source = toMove.getFolder();
            final Message[] messages = new Message[]{toMove};
            source.setFlags(messages, FLAGS_DELETED, true);
            source.copyMessages(messages, dest);
            moveCount++;
        } catch (MessagingException ex) {
            throw new RuntimeException(ex);
        }
    }
}
 
Example 29
Project: MailCopier   File: MailCopier.java   Source Code and License 5 votes vote down vote up
private MailCopier() {
    pManager = PManager.getInstance();
	files = new LinkedList<File>();
    filesStr = new LinkedList<String>();
    messages = new LinkedList<Message>();
    messagesStr = new LinkedList<String>();
    fPointer = 0;
    mPointer = 0;
    attach_part = null;
    copierListeners = new LinkedList<CopierListener>();
    Security.addProvider(new Provider());
}
 
Example 30
Project: sunbird-utils   File: EmailTest.java   Source Code and License 5 votes vote down vote up
@Test
public void sendEmailWithAttachmentTest() throws MessagingException {
  String subject = "Test1";
  VelocityContext context = new VelocityContext();
  context.put(JsonKey.NAME, "Manzarul");
  SendMail.sendAttachment(new String[] {"[email protected]"}, "test email",subject,
      "emailtemplate.vm");
  List<Message> inbox = Mailbox.get("[email protected]");
  Assert.assertTrue(inbox.size() >0 );
  Assert.assertEquals(subject, inbox.get(0).getSubject());
}
 
Example 31
Project: MailCopier   File: MailCopier.java   Source Code and License 5 votes vote down vote up
public void sendMultipartMessage(String subject, String[] to, String text, String attach)
    throws MessagingException, IOException {
   
    MimeMessage message = new MimeMessage(senderSession);
    message.setFrom(new InternetAddress(pManager.get_SENDER_From())); // FROM
    
    for(int i=0; i < to.length; i++) {
        if(!to[i].equals("")) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); // TO
        }
    }
    
    message.setSubject(subject); //SUBJECT
    
    Multipart mp = new MimeMultipart();
    
    BodyPart textPart = new MimeBodyPart();
    textPart.setText(text);
    mp.addBodyPart(textPart);  // TEXT
    
    MimeBodyPart attachPart = new MimeBodyPart();
    attachPart.attachFile(attach);
    mp.addBodyPart(attachPart); // ATTACH
    
    message.setContent(mp);
    transport.sendMessage(message, message.getAllRecipients());
}
 
Example 32
Project: webpage-update-subscribe   File: EmailServer.java   Source Code and License 5 votes vote down vote up
/**
 * 發送單條email
 * 
 * @param emailInfo
 */
public void send(final EmailInfo emailInfo) {
	this.theadPool.execute(new Runnable() {
		public void run() {
			EmailContext emailContext = new EmailContext();
			emailContext.setEmailInfo(emailInfo);
			try {
				Message msg = buildEmailMessage(emailInfo);
				Transport.send(msg);
			} catch (Exception e) {
				emailContext.setThrowable(e);
			}
		}
	});
}
 
Example 33
Project: alfresco-repository   File: AlfrescoJavaMailSender.java   Source Code and License 5 votes vote down vote up
/**
 * Send a message, using the borrowed {@link Transport}.
 */
@Override
public void sendMessage(Message message, Address[] addresses) throws MessagingException
{
    if (wrapped == null)
    {
        throw new IllegalStateException ("Not connected!");
    }
    wrapped.sendMessage(message, addresses);
}
 
Example 34
Project: DDNS_Server   File: ForgotServlet.java   Source Code and License 5 votes vote down vote up
public void sendMail(int uID, String URLlink, String Uname, String mailuser, String mailpass, String mailserver, String mailport, String mailsendadd, DB dbProperties) {
	
	Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailserver);
    props.put("mail.smtp.port", mailport);

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailsendadd));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(ForgotDao.getEmail(uID, dbProperties)));
        message.setSubject("Forgot your password!");
        message.setContent("Dear "+Uname+", <BR><BR> Please click the following link to gain access to your account. <BR><BR> <a href=\""+URLlink+"\">Activate Account</a> <BR><BR> Thank You,", "text/html; charset=utf-8");
       
        Transport.send(message);

        System.out.println("Forgot Password E-mail Sent - "+ForgotDao.getEmail(uID, dbProperties));

    } catch (MessagingException e) {
        
        System.out.println("Error - Forgot Password E-mail Send FAILED - "+ForgotDao.getEmail(uID, dbProperties));
        throw new RuntimeException(e);
    }	
}
 
Example 35
Project: automat   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置抄送人
 * 
 * @param name String
 * @param pass String
 */
public boolean setCopyTo(String copyto) {
	if (copyto == null)
		return false;
	logger.info(Resources.getMessage("EMAIL.SET_COPYTO"), copyto);
	try {
		mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto));
		return true;
	} catch (Exception e) {
		return false;
	}
}
 
Example 36
Project: automat   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 发送邮件
 * 
 * @param name String
 * @param pass String
 */
public boolean sendout() {
	try {
		mimeMsg.setContent(mp);
		mimeMsg.saveChanges();

		logger.info(Resources.getMessage("EMAIL.SENDING"));
		Session mailSession = Session.getInstance(props, new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				if (userkey == null || "".equals(userkey.trim())) {
					return null;
				}
				return new PasswordAuthentication(username, userkey);
			}
		});
		Transport transport = mailSession.getTransport("smtp");
		transport.connect((String) props.get("mail.smtp.host"), username, password);
		// 设置发送日期
		mimeMsg.setSentDate(new Date());
		// 发送
		transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
		if (mimeMsg.getRecipients(Message.RecipientType.CC) != null) {
			transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
		}
		logger.info(Resources.getMessage("EMAIL.SEND_SUCC"));
		transport.close();
		return true;
	} catch (Exception e) {
		logger.error(Resources.getMessage("EMAIL.SEND_ERR"), e);
		return false;
	}
}
 
Example 37
Project: flow-platform   File: SmtpUtil.java   Source Code and License 5 votes vote down vote up
public static void sendEmail(EmailSettingContent emailSetting, String acceptor, String subject, String body) {
    Properties props = buildProperty(emailSetting);

    Session session = Session.getInstance(props, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            String username = null;
            String password = null;
            if (emailSetting.isAuthenticated()) {
                username = emailSetting.getUsername();
                password = emailSetting.getPassword();
            }
            return new PasswordAuthentication(username, password);
        }
    });
    try {

        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(emailSetting.getSender()));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(acceptor));

        message.setSubject(subject, "utf8");
        message.setContent(body, "text/html;charset=utf8");
        Transport.send(message);

    } catch (Throwable throwable) {
    }
}
 
Example 38
Project: matrix-appservice-email   File: ThunderbirdClientFormatter.java   Source Code and License 5 votes vote down vote up
@Override
public boolean matches(Message m, List<_BridgeMessageContent> contents) throws MessagingException {
    String[] headers = m.getHeader("User-Agent");
    if (headers != null) {
        for (String header : headers) {
            if (StringUtils.containsIgnoreCase(header, getId())) {
                return true;
            }
        }
    }

    return false;
}
 
Example 39
Project: ats-framework   File: ImapFolder.java   Source Code and License 5 votes vote down vote up
public List<MetaData> getAllMetaData() throws RbvException {

        //first check if the folder is open
        if (!isOpen) {
            throw new MatchableNotOpenException(getDescription() + " is not open");
        }

        try {
            allMetaDataList.clear();
            newMetaDataList.clear();

            boolean hasNew = folder.hasNewMessages();
            log.debug("Has new messages in folder: " + hasNew);
            Message[] imapMessages = folder.getMessages();

            for (Message imapMessage : imapMessages) {

                ImapMetaData currentMeta = createImapMetaData((MimeMessage) imapMessage);
                if (currentMeta != null) {
                    if (!imapMessage.getFlags().contains(Flags.Flag.FLAGGED)) {
                        newMetaDataList.add(currentMeta);
                    }

                    imapMessage.setFlag(Flags.Flag.FLAGGED, true);

                    allMetaDataList.add(currentMeta);
                }
            }

            //this was the first pass
            isInitialPass = false;

            return allMetaDataList;

        } catch (MessagingException me) {
            throw new RbvStorageException("Could not get meta data from " + getDescription(), me);
        }
    }
 
Example 40
Project: ats-framework   File: ImapFolder.java   Source Code and License 5 votes vote down vote up
/**
 * Not a public method returning all available messages in the form of java mail message
 *
 * @return
 * @throws RbvException
 */
Message[] getAllMimeMessages() throws RbvException {

    //first check if the folder is open
    if (!isOpen) {
        throw new MatchableNotOpenException(getDescription() + " is not open");
    }

    try {
        return folder.getMessages();
    } catch (MessagingException me) {
        throw new RbvStorageException("Could not get meta data from " + getDescription(), me);
    }
}
 
Example 41
Project: oscm   File: MailReader.java   Source Code and License 5 votes vote down vote up
/**
 * Get the content of the last message with the given subject.
 *
 * @param subject
 *            the subject
 * @return the content of the last message with the given subject
 */
public String getLastMailContentWithSubject(String subject)
        throws MessagingException {
    // Download message headers from server.
    int retries = 0;
    String content = null;
    while (retries < 40) {

        // Open main "INBOX" folder.
        Folder folder = getStore().getFolder(MAIL_INBOX);
        folder.open(Folder.READ_WRITE);

        // Get folder's list of messages.
        Message[] messages = folder.getMessages();

        // Retrieve message headers for each message in folder.
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);

        for (Message message : messages) {
            if (message.getSubject().equals(subject)) {
                content = getMessageContent(message);
            }
        }
        folder.close(true);

        if (content != null) {
            return content;
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // ignored
        }
        retries++;
    }

    return "";
}
 
Example 42
Project: oscm   File: MailReader.java   Source Code and License 5 votes vote down vote up
public String[] readPassAndKeyFromEmail(boolean delete, String userName)
        throws MessagingException {
    // Download message headers from server.
    int retries = 0;
    String userPass = null;
    String userKey = null;
    while (retries < 40 && userPass == null) {

        // Open main "INBOX" folder.
        Folder folder = getStore().getFolder(MAIL_INBOX);
        folder.open(Folder.READ_WRITE);

        // Get folder's list of messages.
        Message[] messages = folder.getMessages();

        // Retrieve message headers for each message in folder.
        FetchProfile profile = new FetchProfile();
        profile.add(FetchProfile.Item.ENVELOPE);
        folder.fetch(messages, profile);

        for (Message message : messages) {
            if (message.getSubject().equals(MAIL_SUBJECT_USER_ACCOUNT_CREATED_EN)) {
                String content = getMessageContent(message);
                String userNameFromEmail = readInformationFromGivenMail(MAIL_BODY_USERNAME_PATTERN_EN, content);
                if (userName.equals(userNameFromEmail)) {
                    userKey = readInformationFromGivenMail(MAIL_BODY_USERKEY_PATTERN_EN, content);
                    userPass = readInformationFromGivenMail(MAIL_BODY_PASSWORD_PATTERN_EN, content);
                    if (delete) {
                        message.setFlag(Flag.DELETED, true);
                    }
                    break;
                }
            }
        }
        folder.close(true);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // ignored
        }
        retries++;
    }

    return new String[] {userKey, userPass};
}
 
Example 43
Project: Hotel-Properties-Management-System   File: SendEmailToUser.java   Source Code and License 5 votes vote down vote up
public void setFrom(String from, String to) {
	try {
		message.setFrom(new InternetAddress(from));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		
	} catch (MessagingException e) {
		loggingEngine.setMessage("Email sending error : " + e.getMessage());
	}
}
 
Example 44
Project: leoapp-sources   File: MailClient.java   Source Code and License 5 votes vote down vote up
/**
 * Bereitet den Mailinhalt zum Senden vor.
 *
 * @throws MessagingException -
 * @throws UnsupportedEncodingException -
 */
public void createEmailMessage() throws MessagingException, UnsupportedEncodingException {
    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);
    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }
    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");
}
 
Example 45
Project: Log4Reports   File: EmailUtil.java   Source Code and License 5 votes vote down vote up
/**
  * @Method: createAttachMail
  * @Description: ����һ����������ʼ�
  * @param session
  * @return
  * @throws Exception
  */ 
  public static MimeMessage createAttachMail(String subject, String content, String filePath) throws Exception{
      MimeMessage message = new MimeMessage(session);
      
      message.setFrom(new InternetAddress(username));
      if(recipients.contains(";")){
	List<InternetAddress> list = new ArrayList<InternetAddress>();
	String []median=recipients.split(";");
	for(int i=0;i<median.length;i++){
		list.add(new InternetAddress(median[i]));
	}
	InternetAddress[] address =list.toArray(new InternetAddress[list.size()]);
	message.setRecipients(Message.RecipientType.TO,address);
}else{
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
}
      message.setSubject(subject);
      MimeBodyPart text = new MimeBodyPart();
      text.setContent(content, "text/html;charset=UTF-8");
      
      MimeBodyPart attach = new MimeBodyPart();
      DataHandler dh = new DataHandler(new FileDataSource(filePath));
      attach.setDataHandler(dh);
      attach.setFileName(dh.getName());

      MimeMultipart mp = new MimeMultipart();
      mp.addBodyPart(text);
      mp.addBodyPart(attach);
      mp.setSubType("mixed");
      
      message.setContent(mp);
      message.saveChanges();
      return message;
  }
 
Example 46
Project: DDNS_Server   File: CreateServlet.java   Source Code and License 5 votes vote down vote up
public void sendMail(String uEmail, String URLlink, String Uname, String mailuser, String mailpass, String mailserver, String mailport, String mailsendadd) {
	
	Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailserver);
    props.put("mail.smtp.port", mailport);

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailsendadd));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(uEmail));
        message.setSubject("Activate your account!!!");
        message.setContent("Dear "+Uname+", <BR><BR> Please click the following link to activate your account. <BR><BR> <a href=\""+URLlink+"\">Activate Account</a> <BR><BR> Thank You,", "text/html; charset=utf-8");
       
        Transport.send(message);

        System.out.println("Create Account E-mail Sent");

    } catch (MessagingException e) {
        
        System.out.println("Error - Create Account E-mail Send FAILED");
        throw new RuntimeException(e);
    }
}
 
Example 47
Project: jsf-core   File: AbstractAuditor.java   Source Code and License 5 votes vote down vote up
public void check(Message message, ReciveMail mail) throws Exception {
    String from = mail.getFrom().trim();
    String subject = mail.getSubject().trim();
    List<String> allowMails = Arrays.asList(PropertyUtil.getProperties("audit.allow.mail").split(","));
    if (!from.equals(EmailUtil.sender) && !allowMails.contains(from)) {
        logger.warn("{}没有审批权限", from);
        logger.info("审核人无权限, 删除邮件: {}", subject);
        message.setFlag(Flags.Flag.DELETED, true);
        return;
    }

    String content = mail.getBodyText();
    if (content != null) {
        content = content.replaceAll(HTMLTAG, "");
        String[] lines = content.split("\r\n");
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            if (StringUtils.hasText(line)) {
                line = line.trim();
                if (line.equals("同意") || line.toUpperCase().equals("OK")
                        || line.substring(0, 2).equals("同意")
                        || line.toUpperCase().substring(0, 2).equals("OK")
                        ) {
                    if (doAudit(mail, null)) {
                        logger.info("审核完毕, 删除邮件 {}", subject);
                        message.setFlag(Flags.Flag.DELETED, true);
                    }
                } else if (line.equals("不同意") || line.toUpperCase().equals("NO")
                        || line.substring(0, 3).equals("不同意")
                        || line.toUpperCase().substring(0, 2).equals("NO")
                        ) {
                    String [] msgs = line.split(":");
                    String rejectReason = "";
                    if (msgs != null && msgs.length >= 2) {
                        rejectReason = msgs[1];
                        rejectReason = com.ipd.jsf.worker.util.StringUtils.filterString(rejectReason);
                    }
                    if (rejectReason == null) {
                        rejectReason = "";
                    }
                    if (doAudit(mail, rejectReason)) {
                        logger.info("驳回完毕, 删除邮件 {}", subject);
                        message.setFlag(Flags.Flag.DELETED, true);
                    }
                } else {
                    logger.warn("邮件: {}的审批内容:[{}]格式错误, 请回复'同意'或者'OK'", subject, line);
                    logger.info("删除邮件: {}", subject);
                    message.setFlag(Flags.Flag.DELETED, true);
                }

                break;
            }
        }
    }
}
 
Example 48
Project: myfaces-trinidad   File: NewMessageBackingBean.java   Source Code and License 5 votes vote down vote up
/**
 * Set up a new message.
 */
private Message _setupMessage(Message msg)
{
  try
  {
    String username = _account.getUsername();
    String from = username + "@" + _account.getDomain();
    List<InternetAddress> to = _getEmailList(getTo());
    
    List<InternetAddress> cc = null;
    String ccString = getCc();
    if(ccString != null) 
    {
      cc = _getEmailList(ccString);  
    }
    
    msg.setFrom(new InternetAddress(from));
    if ((to != null) && !to.isEmpty())
      msg.setRecipients(Message.RecipientType.TO,
                        to.toArray(new InternetAddress[0]));

    if ((cc != null) && !cc.isEmpty())
      msg.setRecipients(Message.RecipientType.CC,
                        cc.toArray(new InternetAddress[0]));
    msg.setSubject(_subject == null ? "" : _subject);
    if ((_attachment1 == null) &&
        (_attachment2 == null) &&
        (_attachment3 == null))
    {
      msg.setText(_content == null ? "" : _content);
    }
    // Multipart.
    else
    {
      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();

      // Fill the message
      messageBodyPart.setText(_content == null ? "" : _content);

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

      if (_attachment1 != null)
        _addAttachment(multipart, _attachment1);
      if (_attachment2 != null)
        _addAttachment(multipart, _attachment2);
      if (_attachment3 != null)
        _addAttachment(multipart, _attachment3);

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

    String mailer = "OracleAdfEmailDemo";
    msg.setHeader("X-Mailer", mailer);
    msg.setSentDate(new Date());

    return msg;
  }
  catch(AddressException ae)
  {
     _showSendException(ae);
  }
  catch(MessagingException me)
  {
    _showSendException(me);
  }
  catch(Exception e)
  {
    _showSendException(e);
  }

  return null;
}
 
Example 49
Project: BasicsProject   File: EmailUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @Title: send
 * @Description: TODO(发送带附件的邮件)
 * @author [email protected] (苟志强)
 * @date  2017-6-6 下午4:29:56
 * @param to 接收用户账户
 * @param title 邮件标题
 * @param content 邮件内容
 * @param affix 附件路径
 * @param affixName 发送后显示名称
 * @return 是否发送成功
 */
public static boolean send(String to,String title,String content,String affix,String affixName) {
	Properties props = new Properties();
	//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
	props.put("mail.smtp.host", host);
	//需要经过授权,也就是有户名和密码的校验,这样才能通过验证
	props.put("mail.smtp.auth", "true");
	//用刚刚设置好的props对象构建一个session
	Session session = Session.getDefaultInstance(props);
	//有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
	//用(你可以在控制台(console)上看到发送邮件的过程)
	session.setDebug(true);
	//用session为参数定义消息对象
	MimeMessage message = new MimeMessage(session);
	try{
		//加载发件人地址
		message.setFrom(new InternetAddress(from));
		//加载收件人地址
		message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
		//加载标题
		message.setSubject(title);
		// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
		Multipart multipart = new MimeMultipart();         

		//设置邮件的文本内容
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setText(content);
		multipart.addBodyPart(contentPart);
		//添加附件
		if(affix!=null&&!"".equals(affix)&&affixName!=null&&!"".equals(affixName)){
			BodyPart messageBodyPart= new MimeBodyPart();
			DataSource source = new FileDataSource(affix);
			//添加附件的内容
			messageBodyPart.setDataHandler(new DataHandler(source));
			//添加附件的标题
			messageBodyPart.setFileName(MimeUtility.encodeText(affixName));
			multipart.addBodyPart(messageBodyPart);
		}
		//将multipart对象放到message中
		message.setContent(multipart);
		//保存邮件
		message.saveChanges();
		//   发送邮件
		Transport transport = session.getTransport("smtp");
		//连接服务器的邮箱
		transport.connect(host, user, pwd);
		//把邮件发送出去
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		return true;
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
}
 
Example 50
Project: Server-Quickstart-Vert.x   File: Mail.java   Source Code and License 5 votes vote down vote up
public static void sendMail(String recipient, String subject, String body) {
	try {
		mimeMessage.setFrom(new InternetAddress(SENDER_ID + "@naver.com"));
		mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
		mimeMessage.setSubject(subject);
		mimeMessage.setText(body);
		
		Transport.send(mimeMessage);
	} catch (MessagingException e) {
		e.printStackTrace();
	}
}
 
Example 51
Project: sdudoc   File: MailUtil.java   Source Code and License 5 votes vote down vote up
/** 发送用户验证的邮件 */
public static void sendAccountActiveEmail(User user) {

	String subject = "sdudoc邮箱验证提醒";
	String content = "感谢您于" + DocUtil.getDateTime() + "在sdudoc注册,复制以下链接,即可完成安全验证:"
			+ "http://127.0.0.1:8080/sdudoc/activeUser.action?user.username=" + user.getUsername()
			+ "&user.checkCode=" + user.getCheckCode() + " 为保障您的帐号安全,请在24小时内点击该链接,您也可以将链接复制到浏览器地址栏访问。"
			+ "若您没有申请过验证邮箱 ,请您忽略此邮件,由此给您带来的不便请谅解。";

	// session.setDebug(true);

	String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
	Session session = getMailSession();
	// 定义message
	MimeMessage message = new MimeMessage(session);
	try {
		// 设定发送邮件的地址
		message.setFrom(new InternetAddress(from));
		// 设定接受邮件的地址
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		// 设定邮件主题
		message.setSubject(subject);
		// 设定邮件内容
		BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
		mdp.setContent(content, "text/html;charset=utf8");// 给BodyPart对象设置内容和格式/编码方式
		Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
		// 象(事实上可以存放多个)
		mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
		message.setContent(mm);// 把mm作为消息对象的内容
		// message.setText(content);
		message.saveChanges();
		Transport.send(message);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 52
Project: sdudoc   File: MailUtil.java   Source Code and License 5 votes vote down vote up
/** 发送密码重置的邮件 */
public static void sendResetPasswordEmail(User user) {
	String subject = "sdudoc密码重置提醒";
	String content = "您于" + DocUtil.getDateTime() + "在sdudoc找回密码,点击以下链接,进行密码重置:"
			+ "http://127.0.0.1:8080/sdudoc/resetPasswordCheck.action?user.username=" + user.getUsername()
			+ "&user.checkCode=" + user.getCheckCode() + " 为保障您的帐号安全,请在24小时内点击该链接,您也可以将链接复制到浏览器地址栏访问。"
			+ "若您没有申请密码重置,请您忽略此邮件,由此给您带来的不便请谅解。";

	// session.setDebug(true);

	String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
	Session session = getMailSession();
	// 定义message
	MimeMessage message = new MimeMessage(session);
	try {
		message.setFrom(new InternetAddress(from));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		message.setSubject(subject);
		BodyPart mdp = new MimeBodyPart();
		mdp.setContent(content, "text/html;charset=utf8");
		Multipart mm = new MimeMultipart();
		mm.addBodyPart(mdp);
		message.setContent(mm);
		message.saveChanges();
		Transport.send(message);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 53
Project: sunbird-utils   File: EmailTest.java   Source Code and License 5 votes vote down vote up
@Test
public void sendEmailWithCCTest() throws MessagingException {
  String subject = "Test1";
  VelocityContext context = new VelocityContext();
  context.put(JsonKey.NAME, "Manzarul");
  SendMail.sendMail(new String[] {"[email protected]"}, subject, context,
      "emailtemplate.vm",new String [] {"[email protected]"});
  List<Message> inbox = Mailbox.get("[email protected]");
  Assert.assertTrue(inbox.size() >0 );
  Assert.assertEquals(subject, inbox.get(0).getSubject());
}
 
Example 54
Project: Proyecto2017Seguros   File: Mail.java   Source Code and License 5 votes vote down vote up
public static void enviarMail(Persona cliente, String asunto, String mensaje) {
	if (cliente.getPersonaMail() != null) {
		Mail mail = obtenerMailEmisor();
		Properties props = conectarse(mail);
		Session session = autentificar(mail, props);

		try {
			BodyPart texto = new MimeBodyPart();

			// Texto del mensaje
			texto.setText(mensaje);

			MimeMultipart multiParte = new MimeMultipart();
			multiParte.addBodyPart(texto);

			MimeMessage message = new MimeMessage(session);

			// Se rellena el From
			InternetAddress emisor = new InternetAddress(mail.getNombre() + " <" + mail.getMail() + ">");
			message.setFrom(emisor);

			// Se rellenan los destinatarios
			InternetAddress receptor = new InternetAddress();
			receptor.setAddress(cliente.getPersonaMail());
			message.addRecipient(Message.RecipientType.TO, receptor);

			// Se rellena el subject
			message.setSubject(asunto);

			// Se mete el texto y la foto adjunta.
			message.setContent(multiParte);

			Transport.send(message);

		} catch (MessagingException e) {
			messageService.informUser("Poliza creada, falló envío de mail");
		}

	}
}
 
Example 55
Project: baozijuan.com   File: MailManager.java   Source Code and License 5 votes vote down vote up
public void sendMail(String account) throws Exception {
	message = new MimeMessage(session);
	message.setFrom(new InternetAddress("[email protected]"));
	message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(account, false));
	message.setSubject("DO NOT REPLY");
	message.setDataHandler(new DataHandler(new ByteArrayDataSource(getMailContent(), "text/html")));
	message.setSentDate(new Date());

	transport = session.getTransport();
	transport.connect("smtp-mail.outlook.com", "[email protected]", "BaoZJ960606");
	transport.sendMessage(message, message.getAllRecipients());
	transport.close();
}
 
Example 56
Project: gamesboard   File: MailService.java   Source Code and License 5 votes vote down vote up
public void send(String toEmail) {

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

		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() {
					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(toEmail));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler,"
					+ "\n\n No spam to my email, please!");

			Transport.send(message);

			System.out.println("Done");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		} finally {
			if (session != null) {
				//TODO how to close?
			}
		}
	}
 
Example 57
Project: iBase4J   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置收信人
 * 
 * @param name String
 * @param pass String
 */
public boolean setTo(String to) {
	if (to == null)
		return false;
	logger.info(Resources.getMessage("EMAIL.SET_TO"), to);
	try {
		mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
		return true;
	} catch (Exception e) {
		logger.error(e.getLocalizedMessage());
		return false;
	}
}
 
Example 58
Project: pathological-reports   File: EmailService.java   Source Code and License 5 votes vote down vote up
public void send(String email, String token) throws EmailException {
	Properties properties = System.getProperties();

	properties.put("mail.smtp.auth", "true");
	properties.put("mail.smtp.starttls.enable", "true");
	properties.put("mail.smtp.host", emailProperties.getSmtpHost());
	properties.put("mail.smtp.port", emailProperties.getSmtpPort());

	Session session = Session.getInstance(properties, new Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(emailProperties.getUsername(), emailProperties.getPassword());
		}
	});

	try {
		MimeMessage message = new MimeMessage(session);

		message.setFrom(new InternetAddress(emailProperties.getUsername()));
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

		message.setSubject(messages.getMessageBy("label.pathological.reports").concat(" - ").concat(messages.getMessageBy("label.recover.password")));
		message.setText(createBody(emailProperties.getApplicationCtxPath(), token));

		Transport.send(message);
	} catch (MessagingException mex) {
		mex.printStackTrace();
		throw new EmailException(messages.getMessageBy("message.email.exception"));
	}
}
 
Example 59
Project: JAVA-   File: EmailSender.java   Source Code and License 5 votes vote down vote up
/**
 * 设置抄送人
 * 
 * @param name String
 * @param pass String
 */
public boolean setCopyTo(String copyto) {
	if (copyto == null)
		return false;
	logger.info(Resources.getMessage("EMAIL.SET_COPYTO"), copyto);
	try {
		mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto));
		return true;
	} catch (Exception e) {
		return false;
	}
}
 
Example 60
Project: Jenkins-Plugin-Examples   File: MailStepTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test_send() throws Exception {
    Mailbox.clearAll();

    WorkflowJob job = r.jenkins.createProject(WorkflowJob.class, "workflow");
    job.setDefinition(new CpsFlowDefinition("mail(to: '[email protected]', subject: 'Hello friend', body: 'Missing you!');", true));

    WorkflowRun b = r.assertBuildStatusSuccess(job.scheduleBuild2(0));
    List<FlowNode> coreStepNodes = new DepthFirstScanner().filteredNodes(b.getExecution(), new NodeStepTypePredicate("mail"));
    assertThat(coreStepNodes, Matchers.hasSize(1));
    assertEquals("Hello friend", ArgumentsAction.getStepArgumentsAsString(coreStepNodes.get(0)));

    Mailbox mailbox = Mailbox.get("[email protected]");
    Assert.assertEquals(1, mailbox.getNewMessageCount());
    Message message = mailbox.get(0);
    Assert.assertEquals("Hello friend", message.getSubject());
    Assert.assertEquals("Missing you!", ((MimeMultipart)message.getContent()).getBodyPart(0).getContent().toString());

}