javax.mail.Transport#send ( )源码实例Demo

下面列出了javax.mail.Transport#send ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TwrpBuilder   文件: GMail.java
@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;
}
 
源代码2 项目: uyuni   文件: SmtpMail.java
/** {@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);
    }
}
 
源代码3 项目: unitime   文件: JavaMailWrapper.java
@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.");
	}
}
 
源代码4 项目: cacheonix-core   文件: MailLogger.java
/**
 *  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);
}
 
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 );
    }
}
 
源代码6 项目: redesocial   文件: Enviar_email.java
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);
      }
}
 
源代码7 项目: oodt   文件: MailTask.java
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());
  }

}
 
源代码8 项目: juddi   文件: SMTPNotifier.java
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;
	}
 
源代码9 项目: sdudoc   文件: MailUtil.java
/** 发送密码重置的邮件 */
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();
	}
}
 
源代码10 项目: SensorWebClient   文件: MailSender.java
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;
}
 
源代码11 项目: entando-components   文件: MailManager.java
@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;
}
 
源代码12 项目: tech-gallery   文件: EmailServiceImpl.java
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);
  }
}
 
源代码13 项目: tomee   文件: EmailService.java
@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";
}
 
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);
    }
}
 
源代码15 项目: subethasmtp   文件: MessageContentTest.java
/** */
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);
}
 
public void sendTheEmail() {
	try {
		Transport.send(message);
		
	} catch (MessagingException e) {
		loggingEngine.setMessage("Cannot send email! : " + e.getMessage());
	}
}
 
源代码17 项目: lemon   文件: JavamailService.java
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);
    }
}
 
源代码18 项目: roboconf-platform   文件: EmailCommandExecution.java
@Override
public void execute() throws CommandException {

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

	} catch( Exception e ) {
		throw new CommandException( e );
	}
}
 
源代码19 项目: disconf   文件: SimpleMailSender.java
/**
 * 以文本格式发送邮件
 *
 * @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;
}
 
源代码20 项目: scriptella-etl   文件: MailConnection.java
/**
 * 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);
}