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

The following examples show how to use javax.mail.Transport#sendMessage() . 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: EmailNotifierEngine.java    From repairnator with MIT License 7 votes vote down vote up
public void notify(String subject, String message) {
    if (this.from != null && !this.to.isEmpty()) {
        Message msg = new MimeMessage(this.session);

        try {
            Address[] recipients = this.to.toArray(new Address[this.to.size()]);
            Transport transport = this.session.getTransport();
            
            msg.setFrom(this.from);
            msg.addRecipients(Message.RecipientType.TO, recipients);
            msg.setSubject(subject);
            msg.setText(message);
            
            transport.connect();
            transport.sendMessage(msg, recipients);
            transport.close();
        } catch (MessagingException e) {
            logger.error("Error while sending notification message '" + subject + "'", e);
        }
    } else {
        logger.warn("From is null or to is empty. Notification won't be send.");
    }

}
 
Example 2
Source File: Pop3Util.java    From anyline with Apache License 2.0 7 votes vote down vote up
/** 
 *  
 * @param fr 发送人姓名 
 * @param to 收件人地址 
 * @param title 邮件主题 
 * @param content  邮件内容 
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][centent:{}]", fr, to, title, content); 
	try { 
		Session mailSession = Session.getDefaultInstance(props); 
		Message msg = new MimeMessage(mailSession); 
		msg.setFrom(new InternetAddress(config.ACCOUNT, fr)); 
		msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); 
		msg.setSubject(title); 
		msg.setContent(content, "text/html;charset=UTF-8"); 
		msg.saveChanges(); 
		Transport transport = mailSession.getTransport("smtp"); 
		transport.connect(config.HOST, config.ACCOUNT, config.PASSWORD); 
		transport.sendMessage(msg, msg.getAllRecipients()); 
		transport.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
		return false; 
	} 

	return true; 
}
 
Example 3
Source File: MailUtil.java    From anyline with Apache License 2.0 7 votes vote down vote up
/** 
 *  
 * @param fr		发送人姓名  fr		发送人姓名
 * @param to		收件人地址  to		收件人地址
 * @param title		邮件主题  title		邮件主题
 * @param content	邮件内容  content	邮件内容
 * @return return
 */ 
public boolean send(String fr, String to, String title, String content) { 
	log.warn("[send email][fr:{}][to:{}][title:{}][content:{}]", fr,to,title,content);
	try { 
		Session mailSession = Session.getDefaultInstance(props); 
		Message msg = new MimeMessage(mailSession); 
		msg.setFrom(new InternetAddress(config.ACCOUNT,fr)); 
		msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); 
		msg.setSubject(title + ""); 
		msg.setContent(content + "", "text/html;charset=UTF-8"); 
		msg.saveChanges(); 
		Transport transport = mailSession.getTransport("smtp"); 
		transport.connect(config.HOST,
				config.ACCOUNT, 
				config.PASSWORD);
		transport.sendMessage(msg, msg.getAllRecipients()); 
		transport.close(); 
	} catch (Exception e) { 
		e.printStackTrace(); 
		return false; 
	} 

	return true; 
}
 
Example 4
Source File: MailSender.java    From iaf with Apache License 2.0 6 votes vote down vote up
private void putOnTransport(Session session, Message msg) throws SenderException {
	// connect to the transport
	Transport transport = null;
	try {
		transport = session.getTransport("smtp");
		transport.connect(getSmtpHost(), getCredentialFactory().getUsername(), getCredentialFactory().getPassword());
		if (log.isDebugEnabled()) {
			log.debug("MailSender [" + getName() + "] connected transport to URL [" + transport.getURLName() + "]");
		}
		transport.sendMessage(msg, msg.getAllRecipients());
	} catch (Exception e) {
		throw new SenderException("MailSender [" + getName() + "] cannot connect send message to smtpHost [" + getSmtpHost() + "]", e);
	} finally {
		if (transport != null) {
			try {
				transport.close();
			} catch (MessagingException e1) {
				log.warn("MailSender [" + getName() + "] got exception closing connection", e1);
			}
		}
	}
}
 
Example 5
Source File: SESService.java    From hellokoding-courses with MIT License 6 votes vote down vote up
public boolean sendMail(String subject, String body) {
    try {
        Properties props = System.getProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.port", mailProperties.getSmtp().getPort());
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailProperties.getTo()));
        msg.setSubject(subject);
        msg.setContent(body, "text/html");

        Transport transport = session.getTransport();
        transport.connect(mailProperties.getSmtp().getHost(), mailProperties.getSmtp().getUsername(), mailProperties.getSmtp().getPassword());
        transport.sendMessage(msg, msg.getAllRecipients());
        return true;
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }

    return false;
}
 
Example 6
Source File: MailSender.java    From openwebflow with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void sendMail(String receiver, String subject, String message) throws Exception
{
	Properties properties = new Properties();
	properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议
	properties.setProperty("mail.smtp.auth", "true");//需要验证

	Session session = Session.getInstance(properties);
	session.setDebug(false);
	//邮件信息
	Message messgae = new MimeMessage(session);
	messgae.setFrom(new InternetAddress(getMailFrom()));//设置发送人
	messgae.setText(message);//设置邮件内容
	messgae.setSubject(subject);//设置邮件主题
	//发送邮件
	Transport tran = session.getTransport();
	tran.connect(getServerHost(), getServerPort(), getAuthUserName(), getAuthPassword());
	tran.sendMessage(messgae, new Address[] { new InternetAddress(receiver) });//设置邮件接收人
	tran.close();

	Logger.getLogger(this.getClass()).debug(String.format("sent mail to <%s>: %s", receiver, subject));
}
 
Example 7
Source File: MailAlert.java    From dble-docs-cn with GNU General Public License v2.0 5 votes vote down vote up
private boolean sendMail(boolean isResolve, ClusterAlertBean clusterAlertBean) {
    try {
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", properties.getProperty(MAIL_SERVER));
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(props);

        Message msg = new MimeMessage(session);
        msg.setSubject("DBLE告警 " + (isResolve ? "RESOLVE\n" : "ALERT\n"));
        StringBuilder builder = new StringBuilder();
        builder.append(groupMailMsg(clusterAlertBean, isResolve));
        msg.setText(builder.toString());
        msg.setFrom(new InternetAddress(properties.getProperty(MAIL_SENDER)));

        Transport transport = session.getTransport();
        transport.connect(properties.getProperty(MAIL_SERVER), properties.getProperty(MAIL_SENDER), properties.getProperty(SENDER_PASSWORD));

        transport.sendMessage(msg, new Address[]{new InternetAddress(properties.getProperty(MAIL_RECEIVE))});
        transport.close();
        //send EMAIL SUCCESS return TRUE
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    //send fail reutrn false
    return false;
}
 
Example 8
Source File: EMailManager.java    From jforgame with Apache License 2.0 5 votes vote down vote up
/**
 * 同步发送邮件
 * @param title
 * @param content
 */
public void sendEmailSync(String title, String content) {
	try { // 1. 创建参数配置, 用于连接邮件服务器的参数配置
		Properties props = new Properties(); // 参数配置
		props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
		props.setProperty("mail.smtp.host", emailConfig.getSenderEmailSMTPHost()); // 发件人的邮箱的 SMTP 服务器地址

		// 2. 根据配置创建会话对象, 用于和邮件服务器交互
		Session session = Session.getInstance(props);
		// 设置为debug模式, 可以查看详细的发送 log
		session.setDebug(true);

		// 4. 根据 Session 获取邮件传输对象
		Transport transport = session.getTransport();
		transport.connect(emailConfig.getSenderEmailAddr(), emailConfig.getSenderEmailPwd());

		for (String receiver : emailConfig.getReceivers()) {
			// 3. 创建一封邮件
			MimeMessage message = createMimeMessage(session, emailConfig.getSenderEmailAddr(), receiver, title, content);
			// 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人,
			// 密送人
			transport.sendMessage(message, message.getAllRecipients());
		}

		// 7. 关闭连接
		transport.close();
	} catch (Exception e) {
		LoggerUtils.error("", e);
	}
}
 
Example 9
Source File: MailUtil.java    From lutece-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Send the message
 *
 * @param msg
 *            the message to send
 * @param transport
 *            the transport used to send the message
 * @throws MessagingException
 *             If a messaging error occured
 * @throws AddressException
 *             If invalid address
 */
private static void sendMessage( Message msg, Transport transport ) throws MessagingException
{
    if ( msg.getAllRecipients( ) != null )
    {
        // Send the message
        transport.sendMessage( msg, msg.getAllRecipients( ) );
    }
    else
    {
        throw new AddressException( "Mail adress is null" );
    }
}
 
Example 10
Source File: MailingListPublisher.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Publish post.
 *
 * @throws MessagingException if an error occurs while publishing.
 * @throws IOException if there are problems with reading file with the post text.
 */
public void publish() throws MessagingException, IOException {
    final Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", true);
    props.put("mail.smtp.host", SMTP_HOST);
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.auth", true);

    final Session session = Session.getInstance(props, null);
    final MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setSubject(String.format(SUBJECT_TEMPLATE, releaseNumber));
    mimeMessage.setFrom(new InternetAddress(username));
    mimeMessage.addRecipients(Message.RecipientType.TO,
            InternetAddress.parse(RECIPIENT_ADDRESS));

    final String post = new String(Files.readAllBytes(Paths.get(postFilename)),
            StandardCharsets.UTF_8);

    final BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setContent(post, "text/plain");

    final Multipart multipart = new MimeMultipart("alternative");
    multipart.addBodyPart(messageBodyPart);
    mimeMessage.setContent(multipart);

    final Transport transport = session.getTransport("smtp");
    transport.connect(SMTP_HOST, username, password);
    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
 
Example 11
Source File: SendMailInvocation.java    From camunda-bpm-mail with Apache License 2.0 5 votes vote down vote up
@Override
public Object invokeTarget() throws Exception {
  Message message = target;

  LOGGER.debug("send '{}'", Mail.from(message));

  Transport transport = mailService.getTransport();
  transport.sendMessage(message, message.getAllRecipients());
  mailService.flush();

  return null;
}
 
Example 12
Source File: MailUtils.java    From SMS2Email with Apache License 2.0 4 votes vote down vote up
public static void sendEmail(String from, String password, Session session, MimeMessage mail) throws Exception {
    Transport transport = session.getTransport();
    transport.connect(from, password);
    transport.sendMessage(mail, mail.getAllRecipients());
    transport.close();
}
 
Example 13
Source File: EmailLogServlet.java    From teamengine with Apache License 2.0 4 votes vote down vote up
public boolean sendLog(String host, String userId, String password,
        String to, String from, String subject, String message,
        File filename) {
    boolean success = true;
    System.out.println("host: " + host);
    System.out.println("userId: " + userId);
    // Fortify Mod: commented out clear text password.
    // System.out.println("password: " + password);
    System.out.println("to: " + to);
    System.out.println("from: " + from);
    System.out.println("subject: " + subject);
    System.out.println("message: " + message);
    System.out.println("filename: " + filename.getName());
    System.out.println("filename: " + filename.getAbsolutePath());

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

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

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

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

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

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

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

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

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

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

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

        // smtphost
        trans.close();

    } catch (MessagingException mex) {
        success = false;
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
    return success;
}
 
Example 14
Source File: MimeMailExample.java    From DKIM-for-JavaMail with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
	
	// read test configuration from test.properties in your classpath
	Properties testProps = TestUtil.readProperties();
	
	// generate string buffered test mail
	StringBuffer mimeMail = new StringBuffer();
	mimeMail.append("Date: ").append(new MailDateFormat().format(new Date())).append("\r\n");
	mimeMail.append("From: ").append(testProps.getProperty("mail.smtp.from")).append("\r\n");
	if (testProps.getProperty("mail.smtp.to") != null) {
		mimeMail.append("To: ").append(testProps.getProperty("mail.smtp.to")).append("\r\n");
	}
	if (testProps.getProperty("mail.smtp.cc") != null) {
		mimeMail.append("Cc: ").append(testProps.getProperty("mail.smtp.cc")).append("\r\n");
	}
	mimeMail.append("Subject: ").append("DKIM for JavaMail: MimeMailExample Testmessage").append("\r\n");
	mimeMail.append("\r\n");
	mimeMail.append(TestUtil.bodyText);

	// get a JavaMail Session object 
	Session session = Session.getDefaultInstance(testProps, null);

	
	
	///////// beginning of DKIM FOR JAVAMAIL stuff
	
	// get DKIMSigner object
	DKIMSigner dkimSigner = new DKIMSigner(
			testProps.getProperty("mail.smtp.dkim.signingdomain"),
			testProps.getProperty("mail.smtp.dkim.selector"),
			testProps.getProperty("mail.smtp.dkim.privatekey"));

	/* set an address or user-id of the user on behalf this message was signed;
	 * this identity is up to you, except the domain part must be the signing domain
	 * or a subdomain of the signing domain.
	 */ 
	dkimSigner.setIdentity("mimemailexample@"+testProps.getProperty("mail.smtp.dkim.signingdomain"));

	// construct the JavaMail message using the DKIM message type from DKIM for JavaMail
	Message msg = new SMTPDKIMMessage(session, new ByteArrayInputStream(mimeMail.toString().getBytes()), dkimSigner);

	///////// end of DKIM FOR JAVAMAIL stuff

	// send the message by JavaMail
	Transport transport = session.getTransport("smtp");
	transport.connect(testProps.getProperty("mail.smtp.host"),
			testProps.getProperty("mail.smtp.auth.user"),
			testProps.getProperty("mail.smtp.auth.password"));
	transport.sendMessage(msg, msg.getAllRecipients());
	transport.close();
}
 
Example 15
Source File: FullExample.java    From DKIM-for-JavaMail with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {

		// read test configuration from test.properties in your classpath
		Properties testProps = TestUtil.readProperties();

		// get a JavaMail Session object 
		Session session = Session.getDefaultInstance(testProps, null);

		
		
		///////// beginning of DKIM FOR JAVAMAIL stuff
		
		// get DKIMSigner object
		DKIMSigner dkimSigner = new DKIMSigner(
				testProps.getProperty("mail.smtp.dkim.signingdomain"),
				testProps.getProperty("mail.smtp.dkim.selector"),
				testProps.getProperty("mail.smtp.dkim.privatekey"));

		/* set an address or user-id of the user on behalf this message was signed;
		 * this identity is up to you, except the domain part must be the signing domain
		 * or a subdomain of the signing domain.
		 */ 
		dkimSigner.setIdentity("fullexample@"+testProps.getProperty("mail.smtp.dkim.signingdomain"));
		
		// get default
		System.out.println("Default headers getting signed if available:");
		TestUtil.printArray(dkimSigner.getDefaultHeadersToSign());

		// the following header will be signed as well if available
		dkimSigner.addHeaderToSign("ASpecialHeader");
		
		// the following header won't be signed
		dkimSigner.removeHeaderToSign("Content-Type");

		// change default canonicalizations
		dkimSigner.setHeaderCanonicalization(Canonicalization.SIMPLE);
		dkimSigner.setBodyCanonicalization(Canonicalization.RELAXED);

		// add length param to the signature, see RFC 4871
		dkimSigner.setLengthParam(true);
		
		// change default signing algorithm
		dkimSigner.setSigningAlgorithm(SigningAlgorithm.SHA1withRSA);

		// add a list of header=value pairs to the signature for debugging reasons 
		dkimSigner.setZParam(true);

		///////// end of DKIM FOR JAVAMAIL stuff
		
		
		

		// construct the JavaMail message using the DKIM message type from DKIM for JavaMail
		Message msg = new SMTPDKIMMessage(session, dkimSigner);
		Multipart mp = new MimeMultipart();
		msg.setFrom(new InternetAddress(testProps.getProperty("mail.smtp.from")));
		if (testProps.getProperty("mail.smtp.to") != null) {
			msg.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(testProps.getProperty("mail.smtp.to"), false));
		}
		if (testProps.getProperty("mail.smtp.cc") != null) {
			msg.setRecipients(Message.RecipientType.CC,
					InternetAddress.parse(testProps.getProperty("mail.smtp.cc"), false));
		}

		msg.setSubject("DKIM for JavaMail: FullExample Testmessage");
		
		MimeBodyPart mbp_msgtext = new MimeBodyPart();
        mbp_msgtext.setText(TestUtil.bodyText);
        mp.addBodyPart(mbp_msgtext);
        
        TestUtil.addFileAttachment(mp, testProps.get("mail.smtp.attachment"));
        
        msg.setContent(mp);

        // send the message by JavaMail
		Transport transport = session.getTransport("smtp"); // or smtps ( = TLS)
		transport.connect(testProps.getProperty("mail.smtp.host"),
				testProps.getProperty("mail.smtp.auth.user"),
				testProps.getProperty("mail.smtp.auth.password"));
		transport.sendMessage(msg, msg.getAllRecipients());
		transport.close();
	}
 
Example 16
Source File: Mail4Customize.java    From DBus with Apache License 2.0 4 votes vote down vote up
@Override
public boolean send(Message msg) {
    boolean isOk = true;
    Transport transport = null;
    try {
        LOG.info(String.format("Address: %s", msg.getAddress()));
        LOG.info(String.format("Subject: %s", msg.getSubject() + ENV));
        LOG.info(String.format("Contents: %s", msg.getContents()));
        LOG.info(String.format("Host: %s", msg.getHost()));
        LOG.info(String.format("Port: %s", msg.getPort()));
        LOG.info(String.format("User name: %s", msg.getUserName()));

        Properties props = new Properties();
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", msg.getHost());

        Session session = Session.getInstance(props);
        // session.setDebug(true);

        MimeMessage message = new MimeMessage(session);
        message.setFrom(msg.getFromAddress());
        message.setRecipients(javax.mail.Message.RecipientType.TO, msg.getAddress());
        message.setSubject(msg.getSubject());

        MimeMultipart mmp = new MimeMultipart();
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setContent(msg.getContents(), "text/html;charset=UTF-8");

        mmp.addBodyPart(mbp);
        mmp.setSubType("mixed");

        message.setContent(mmp);
        message.setSentDate(new Date());

        transport = session.getTransport();
        transport.connect(msg.getHost(), msg.getPort(), msg.getUserName(), msg.getPassword());
        transport.sendMessage(message, message.getAllRecipients());

        LOG.error("mail for customize send email success.");
    } catch (Exception e) {
        isOk = false;
        LOG.error("mail for customize send email fail.", e);
    } finally {
        close(transport);
    }
    return isOk;
}
 
Example 17
Source File: SimpleExample.java    From DKIM-for-JavaMail with Apache License 2.0 4 votes vote down vote up
public static void main(String args[]) throws Exception {
	
	// read test configuration from test.properties in your classpath
	Properties testProps = TestUtil.readProperties();

	// get a JavaMail Session object 
	Session session = Session.getDefaultInstance(testProps, null);

	
	
	///////// beginning of DKIM FOR JAVAMAIL stuff
	
	// get DKIMSigner object
	DKIMSigner dkimSigner = new DKIMSigner(
			testProps.getProperty("mail.smtp.dkim.signingdomain"),
			testProps.getProperty("mail.smtp.dkim.selector"),
			testProps.getProperty("mail.smtp.dkim.privatekey"));

	/* set an address or user-id of the user on behalf this message was signed;
	 * this identity is up to you, except the domain part must be the signing domain
	 * or a subdomain of the signing domain.
	 */ 
	dkimSigner.setIdentity("simpleexample@"+testProps.getProperty("mail.smtp.dkim.signingdomain"));

	// construct the JavaMail message using the DKIM message type from DKIM for JavaMail
	Message msg = new SMTPDKIMMessage(session, dkimSigner);
	
	///////// end of DKIM FOR JAVAMAIL stuff

	
	
	msg.setFrom(new InternetAddress(testProps.getProperty("mail.smtp.from")));
	if (testProps.getProperty("mail.smtp.to") != null) {
		msg.setRecipients(Message.RecipientType.TO,
				InternetAddress.parse(testProps.getProperty("mail.smtp.to"), false));
	}
	if (testProps.getProperty("mail.smtp.cc") != null) {
		msg.setRecipients(Message.RecipientType.CC,
				InternetAddress.parse(testProps.getProperty("mail.smtp.cc"), false));
	}

	msg.setSubject("DKIM for JavaMail: SimpleExample Testmessage");
	msg.setText(TestUtil.bodyText);

	// send the message by JavaMail
	Transport transport = session.getTransport("smtp");
	transport.connect(testProps.getProperty("mail.smtp.host"),
			testProps.getProperty("mail.smtp.auth.user"),
			testProps.getProperty("mail.smtp.auth.password"));
	transport.sendMessage(msg, msg.getAllRecipients());
	transport.close();
}
 
Example 18
Source File: RecoverController.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
private boolean emailPassword(String password, String username, String email) {
    /* Default to protocol smtp when SmtpEncryption is set to "None" */
    String prot = "smtp";

    if (settingsService.getSmtpServer() == null || settingsService.getSmtpServer().isEmpty()) {
        LOG.warn("Can not send email; no Smtp server configured.");
        return false;
    }

    Properties props = new Properties();
    if (settingsService.getSmtpEncryption().equals("SSL/TLS")) {
        prot = "smtps";
        props.put("mail." + prot + ".ssl.enable", "true");
    } else if (settingsService.getSmtpEncryption().equals("STARTTLS")) {
        prot = "smtp";
        props.put("mail." + prot + ".starttls.enable", "true");
    }
    props.put("mail." + prot + ".host", settingsService.getSmtpServer());
    props.put("mail." + prot + ".port", settingsService.getSmtpPort());
    /* use authentication when SmtpUser is configured */
    if (settingsService.getSmtpUser() != null && !settingsService.getSmtpUser().isEmpty()) {
        props.put("mail." + prot + ".auth", "true");
    }

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

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(settingsService.getSmtpFrom()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Airsonic Password");
        message.setText("Hi there!\n\n" +
                "You have requested to reset your Airsonic password.  Please find your new login details below.\n\n" +
                "Username: " + username + "\n" +
                "Password: " + password + "\n\n" +
                "--\n" +
                "Your Airsonic server\n" +
                "airsonic.github.io/");
        message.setSentDate(new Date());

        Transport trans = session.getTransport(prot);
        try {
            if (props.get("mail." + prot + ".auth") != null && props.get("mail." + prot + ".auth").equals("true")) {
                trans.connect(settingsService.getSmtpServer(), settingsService.getSmtpUser(), settingsService.getSmtpPassword());
            } else {
                trans.connect();
            }
            trans.sendMessage(message, message.getAllRecipients());
        } finally {
            trans.close();
        }
        return true;

    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        return false;
    }
}
 
Example 19
Source File: pinpoint_send_email_smtp.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        // Create a Properties object to contain connection configuration information.
    	Properties props = System.getProperties();
    	props.put("mail.transport.protocol", "smtp");
    	props.put("mail.smtp.port", port);
    	props.put("mail.smtp.starttls.enable", "true");
    	props.put("mail.smtp.auth", "true");

        // Create a Session object to represent a mail session with the specified properties.
    	Session session = Session.getDefaultInstance(props);

        // Create a message with the specified information.
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(senderAddress,senderName));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses));
        msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses));
        msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddresses));

        msg.setSubject(subject);
        msg.setContent(htmlBody,"text/html");

        // Add headers for configuration set and message tags to the message.
        msg.setHeader("X-SES-CONFIGURATION-SET", configurationSet);
        msg.setHeader("X-SES-MESSAGE-TAGS", tag0);
        msg.setHeader("X-SES-MESSAGE-TAGS", tag1);

        // Create a transport.
        Transport transport = session.getTransport();

        // Send the message.
        try {
            System.out.println("Sending...");

            // Connect to Amazon Pinpoint using the SMTP username and password you specified above.
            transport.connect(smtpEndpoint, smtpUsername, smtpPassword);

            // Send the email.
            transport.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Email sent!");
        }
        catch (Exception ex) {
            System.out.println("The email wasn't sent. Error message: "
                + ex.getMessage());
        }
        finally {
            // Close the connection to the SMTP server.
            transport.close();
        }
    }
 
Example 20
Source File: EmailServiceImpl.java    From publick-sling-blog with Apache License 2.0 4 votes vote down vote up
/**
 * Send an email.
 *
 * @param recipient The recipient of the email
 * @param subject The subject of the email.
 * @param body The body of the email.
 * @return true if the email was sent successfully.
 */
public boolean sendMail(final String recipient, final String subject, final String body) {
    boolean result = false;

    // Create a Properties object to contain connection configuration information.
    java.util.Properties props = System.getProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.port", getPort());

    // Set properties indicating that we want to use STARTTLS to encrypt the connection.
    // The SMTP session will begin on an unencrypted connection, and then the client
    // will issue a STARTTLS command to upgrade to an encrypted connection.
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.starttls.required", "true");

    // Create a Session object to represent a mail session with the specified properties.
    Session session = Session.getDefaultInstance(props);

    // Create a message with the specified information.
    MimeMessage msg = new MimeMessage(session);

    Transport transport = null;

    // Send the message.
    try {
        msg.setFrom(new InternetAddress(getSender()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
        msg.setSubject(subject);
        msg.setContent(body, "text/plain");

        // Create a transport.
        transport = session.getTransport();

        // Connect to email server using the SMTP username and password you specified above.
        transport.connect(getHost(), getSmtpUsername(), getUnobfuscatedSmtpPassword());

        // Send the email.
        transport.sendMessage(msg, msg.getAllRecipients());

        result = true;
    } catch (Exception ex) {
        LOGGER.error("The email was not sent.", ex);
    } finally {
        // Close and terminate the connection.
        try {
            transport.close();
        } catch (MessagingException e) {
            LOGGER.error("Could not close transport", e);
        }
    }

    return result;
}