Java Code Examples for javax.mail.Transport#send()

The following examples show how to use javax.mail.Transport#send() . 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: GMail.java    From TwrpBuilder with GNU General Public License v3.0 6 votes vote down vote up
@Nullable
@Override
protected String doInBackground(String... strings) {
    try {
        MimeMessage message = new MimeMessage(session);
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes()));
        message.setSender(new InternetAddress(sender));
        message.setSubject(subject);
        message.setDataHandler(handler);
        if (recipients.indexOf(',') > 0)
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
        else
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
        Transport.send(message);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 2
Source File: JavaMailWrapper.java    From unitime with Apache License 2.0 6 votes vote down vote up
@Override
public void send() throws MessagingException, UnsupportedEncodingException {
	long t0 = System.currentTimeMillis();
	try {
		if (iMail.getFrom() == null || iMail.getFrom().length == 0)
	        setFrom(ApplicationProperty.EmailSenderAddress.value(), ApplicationProperty.EmailSenderName.value());
        if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0)
        	setReplyTo(ApplicationProperty.EmailReplyToAddress.value(), ApplicationProperty.EmailReplyToName.value());
        iMail.setSentDate(new Date());
        iMail.setContent(iBody);
        iMail.saveChanges();
        Transport.send(iMail);
	} finally {
		long t = System.currentTimeMillis() - t0;
		if (t > 30000)
			sLog.warn("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email.");
		else if (t > 5000)
			sLog.info("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email.");
	}
}
 
Example 3
Source File: SmtpMail.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/** {@inheritDoc} */
public void send() {

    try {
        Address[] addrs = message.getRecipients(RecipientType.TO);
        if (addrs == null || addrs.length == 0) {
            log.warn("Aborting mail message " + message.getSubject() +
                    ": No recipients");
            return;
        }
        Transport.send(message);
    }
    catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " +
                             me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}
 
Example 4
Source File: EmailCommandExecution.java    From roboconf-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void execute() throws CommandException {

	try {
		Message message = getMessageToSend();
		Transport.send( message );

	} catch( Exception e ) {
		throw new CommandException( e );
	}
}
 
Example 5
Source File: MailLogger.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 *  Send the mail
 *
 * @param  aMailhost mail server
 * @param  aFrom from address
 * @param  aToList comma-separated recipient list
 * @param  aSubject mail subject
 * @param  aText mail body
 * @throws Exception if sending message fails
 */
private void sendMail(String aMailhost, String aFrom, String aToList,
        String aSubject, String aText)
    throws Exception
{
    // Get system properties
    final Properties props = System.getProperties();

    // Setup mail server
    props.put("mail.smtp.host", aMailhost);

    // Get session
    final Session session = Session.getDefaultInstance(props, null);

    // Define message
    final MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(aFrom));
    final StringTokenizer t = new StringTokenizer(aToList, ", ", false);
    while (t.hasMoreTokens()) {
        message.addRecipient(
            MimeMessage.RecipientType.TO,
            new InternetAddress(t.nextToken()));
    }
    message.setSubject(aSubject);
    message.setText(aText);

    Transport.send(message);
}
 
Example 6
Source File: JavamailService.java    From lemon with Apache License 2.0 5 votes vote down vote up
public void send(String to, String cc, String bcc, String subject,
        String content, JavamailConfig javamailConfig)
        throws MessagingException {
    logger.debug("send : {}, {}", to, subject);

    try {
        Properties props = createSmtpProperties(javamailConfig);
        String username = javamailConfig.getUsername();
        String password = javamailConfig.getPassword();

        // 创建Session实例对象
        Session session = Session.getInstance(props, new SmtpAuthenticator(
                username, password));
        session.setDebug(false);

        // 创建MimeMessage实例对象
        MimeMessage message = new MimeMessage(session);
        // 设置邮件主题
        message.setSubject(subject);
        // 设置发送人
        message.setFrom(new InternetAddress(username));
        // 设置发送时间
        message.setSentDate(new Date());
        // 设置收件人
        message.setRecipients(RecipientType.TO, InternetAddress.parse(to));
        // 设置html内容为邮件正文,指定MIME类型为text/html类型,并指定字符编码为gbk
        message.setContent(content, "text/html;charset=gbk");

        // 保存并生成最终的邮件内容
        message.saveChanges();

        // 发送邮件
        Transport.send(message);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}
 
Example 7
Source File: SendEmailToUser.java    From Hotel-Properties-Management-System with GNU General Public License v2.0 5 votes vote down vote up
public void sendTheEmail() {
	try {
		Transport.send(message);
		
	} catch (MessagingException e) {
		loggingEngine.setMessage("Cannot send email! : " + e.getMessage());
	}
}
 
Example 8
Source File: MessageContentTest.java    From subethasmtp with Apache License 2.0 5 votes vote down vote up
/** */
private void testEightBitMessage(String body, String charset) throws Exception
{
	MimeMessage message = new MimeMessage(this.session);
	message.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));
	message.setFrom(new InternetAddress("[email protected]"));
	message.setSubject("hello");
	message.setText(body, charset);
	message.setHeader("Content-Transfer-Encoding", "8bit");

	Transport.send(message);
}
 
Example 9
Source File: MailNotification.java    From play-with-hexagonal-architecture with Do What The F*ck You Want To Public License 5 votes vote down vote up
private void sendMailNotification(String emailToSend, String messageEvent) {
    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("[email protected]"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailToSend));
        message.setSubject("File manager sendNotification");
        message.setText(messageEvent);
        Transport.send(message);
    } catch (javax.mail.MessagingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 10
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 11
Source File: EmailServiceImpl.java    From tech-gallery with Apache License 2.0 5 votes vote down vote up
private void sendEmail(EmailConfig email) {
  try {
    Message msg = prepareMessage(email);
    Transport.send(msg);
    registerEmailNotification(email, true);

  } catch (Throwable err) {
    Long notificationId = registerEmailNotification(email, false);
    log.log(Level.SEVERE, "Error when attempting to send email " + notificationId, err);
  }
}
 
Example 12
Source File: MailManager.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public boolean sendMixedMail(String simpleText, String htmlText, String subject, Properties attachmentFiles,
		String[] recipientsTo, String[] recipientsCc, String[] recipientsBcc, String senderCode) throws ApsSystemException {
	if (!isActive()) {
		_logger.info("Sender function disabled : mail Subject " + subject);
		return true;
	}
	Transport bus = null;
	try {
		Session session = this.prepareSession(this.getConfig());
		bus = this.prepareTransport(session, this.getConfig());
		MimeMessage msg = this.prepareVoidMimeMessage(session, subject, recipientsTo, recipientsCc, recipientsBcc, senderCode);
		boolean hasAttachments = attachmentFiles != null && attachmentFiles.size() > 0;
		String multipartMimeType = hasAttachments ? "mixed" : "alternative";
		MimeMultipart multiPart = new MimeMultipart(multipartMimeType);
		this.addBodyPart(simpleText, CONTENTTYPE_TEXT_PLAIN, multiPart);
		this.addBodyPart(htmlText, CONTENTTYPE_TEXT_HTML, multiPart);
		if (hasAttachments) {
			this.addAttachments(attachmentFiles, multiPart);
		}
		msg.setContent(multiPart);
		msg.saveChanges();
		bus.send(msg);
	} catch (Throwable t) {
		throw new ApsSystemException("Error sending mail", t);
	} finally {
		closeTransport(bus);
	}
	return true;
}
 
Example 13
Source File: MailSender.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public static boolean sendDeleteProfileMail(String address, String userID) {
    LOGGER.debug("send delete profile mail to: " + address);

    String link = "?delete=" + userID;
    String text = SesConfig.mailDeleteProfile_en + ": " + "\n\n" +
    SesConfig.mailDeleteProfile_de + ": " + "\n\n" + SesConfig.URL + link;

    Session session = Session.getDefaultInstance(getProperties(), getMailAuthenticator());

    try {
        // send a new message
        Message msg = new MimeMessage(session);

        // set sender and receiver
        msg.setFrom(new InternetAddress(SesConfig.SENDER_ADDRESS));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));

        // set subject
        msg.setSubject(SesConfig.mailSubjectDeleteProfile_en + "/" + SesConfig.mailSubjectDeleteProfile_de);
        msg.setText(text);
        msg.setSentDate(new Date());

        // send mail
        Transport.send(msg);
        LOGGER.debug("mail send succesfully done");
        return true;
    } catch (Exception e) {
        LOGGER.error("Error occured while sending delete profile mail: " + e.getMessage(), e);
    }
    return false;
}
 
Example 14
Source File: MailUtil.java    From sdudoc with MIT 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 15
Source File: SMTPNotifier.java    From juddi with Apache License 2.0 5 votes vote down vote up
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException {

		

		try {
                        log.info("Sending notification email to " + notificationEmailAddress + " from " + getEMailProperties().getProperty("mail.smtp.from", "jUDDI"));
			if (session !=null && notificationEmailAddress != null) {
				MimeMessage message = new MimeMessage(session);
				InternetAddress address = new InternetAddress(notificationEmailAddress);
				Address[] to = {address};
				message.setRecipients(RecipientType.TO, to);
				message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI")));
				//maybe nice to use a template rather then sending raw xml.
				String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES);
				message.setText(subscriptionResultXML, "UTF-8");
                                //message.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;");
				message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.default.subject") + " " 
						+ StringEscapeUtils.escapeHtml(body.getSubscriptionResultsList().getSubscription().getSubscriptionKey()));
				Transport.send(message);
			}
                        else throw new DispositionReportFaultMessage("Session is null!", null);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			throw new DispositionReportFaultMessage(e.getMessage(), null);
		}

		DispositionReport dr = new DispositionReport();
		Result res = new Result();
		dr.getResult().add(res);

		return dr;
	}
 
Example 16
Source File: MailTask.java    From oodt with Apache License 2.0 5 votes vote down vote up
public void run(Metadata metadata, WorkflowTaskConfiguration config)
    throws WorkflowTaskInstanceException {
  Properties mailProps = new Properties();
  mailProps.setProperty("mail.host", "smtp.jpl.nasa.gov");
  mailProps.setProperty("mail.user", "mattmann");
  
  Session session = Session.getInstance(mailProps);

  String msgTxt = "Hello "
      + config.getProperty("user.name")
      + ":\n\n"
      + "You have successfully ingested the file with the following metadata: \n\n"
      + getMsgStringFromMet(metadata) + "\n\n" + "Thanks!\n\n" + "CAS";

  Message msg = new MimeMessage(session);
  try {
    msg.setSubject(config.getProperty("msg.subject"));
    msg.setSentDate(new Date());
    msg.setFrom(InternetAddress.parse(config.getProperty("mail.from"))[0]);
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config
        .getProperty("mail.to"), false));
    msg.setText(msgTxt);
    Transport.send(msg);

  } catch (MessagingException e) {
    throw new WorkflowTaskInstanceException(e.getMessage());
  }

}
 
Example 17
Source File: Enviar_email.java    From redesocial with MIT License 5 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 18
Source File: ExceptionNotificationServiceImpl.java    From telekom-workflow-engine with MIT License 5 votes vote down vote up
private void sendEmail( String from, String to, String subject, String body ){
    log.info( "Sending exception email from:{} to:{} subject:{}", from, to, subject );
    try{
        Properties props = new Properties();
        props.put( "mail.smtp.host", smtpHost );
        if (StringUtils.isNotBlank(smtpPort)) {
            props.put( "mail.smtp.port", smtpPort );
        }
        Authenticator authenticator = null;
        if (StringUtils.isNotBlank(smtpUsername)) {
            props.put( "mail.smtp.auth", true );
            authenticator = new SmtpAuthenticator();
        }
        Session session = Session.getDefaultInstance( props, authenticator );

        Message msg = new MimeMessage( session );
        msg.setFrom( new InternetAddress( from ) );

        InternetAddress[] addresses = InternetAddress.parse( to );
        msg.setRecipients( Message.RecipientType.TO, addresses );

        msg.setSubject( subject );
        msg.setSentDate( new Date() );
        msg.setText( body );
        Transport.send( msg );
    }
    catch( Exception e ){
        log.warn( "Sending email failed: ", e );
    }
}
 
Example 19
Source File: SimpleMailSender.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 以文本格式发送邮件
 *
 * @param mailInfo 待发送的邮件的信息
 */
public static boolean sendTextMail(MailSenderInfo mailInfo) {

    try {

        // 设置一些通用的数据
        Message mailMessage = setCommon(mailInfo);

        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);

        // 发送邮件
        Transport.send(mailMessage);

        return true;

    } catch (MessagingException ex) {

        ex.printStackTrace();
    }

    return false;
}
 
Example 20
Source File: MailConnection.java    From scriptella-etl with Apache License 2.0 2 votes vote down vote up
/**
 * Template method to decouple transport dependency, overriden in test classes.
 *
 * @param message message to send.
 */
protected void send(MimeMessage message) throws MessagingException {
    Transport.send(message);
}