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

The following examples show how to use javax.mail.Transport#connect() . 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: 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 2
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
public static Boolean connect(Properties props)
        throws MessagingException, IOException {
    Properties properties = decryptValues(props);
    Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
                    properties.getProperty("username"),
                    properties.getProperty("password"));
        }
    });
    Transport transport = session.getTransport("smtp");
    transport.connect();
    transport.close();
    return true;
}
 
Example 3
Source File: ConnectionStrategyFactory.java    From smtp-connection-pool with Apache License 2.0 6 votes vote down vote up
public static ConnectionStrategy newConnectionStrategy(final String username, final String password) {
  return new ConnectionStrategy() {
    @Override
    public void connect(Transport transport) throws MessagingException {
      transport.connect(username, password);
    }

    @Override
    public String toString() {
      return "ConnectionStrategy{" +
          "username=" + username +
          '}';
    }

  };
}
 
Example 4
Source File: EmailSender.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
public void send(SendEmailRequest sendEmailRequest) {
    try {
        Session session = session();
        Message message = new MimeMessage(session);
        message.setSubject(sendEmailRequest.subject);
        if (sendEmailRequest.mimeType == MimeType.HTML) {
            message.setContent(sendEmailRequest.content, "text/html;charset=UTF-8");
        } else {
            message.setText(sendEmailRequest.content);
        }

        message.setFrom(new EmailName(session.getProperty("mail.user")).toAddress());
        message.setReplyTo(new Address[]{new EmailName(this.session.getProperty("mail.replyTo")).toAddress()});
        Transport transport = session.getTransport();
        transport.connect();
        transport.sendMessage(message, addresses(sendEmailRequest.to));
        transport.close();
    } catch (MessagingException | UnsupportedEncodingException e) {
        logger.error("failed to send email, to={}, subject={}", sendEmailRequest.to, sendEmailRequest.subject, e);
    }
}
 
Example 5
Source File: ConnectionStrategyFactory.java    From smtp-connection-pool with Apache License 2.0 6 votes vote down vote up
public static ConnectionStrategy newConnectionStrategy(final String host, final int port, final String username, final String password) {
  return new ConnectionStrategy() {
    @Override
    public void connect(Transport transport) throws MessagingException {
      transport.connect(host, port, username, password);
    }

    @Override
    public String toString() {
      return "ConnectionStrategy{" +
          "host=" + host +
          ", port=" + port +
          ", username=" + username +
          '}';
    }
  };
}
 
Example 6
Source File: MailUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 发送电子邮件
 * 
 * @param smtpHost
 *            发信主机
 * @param receiver
 *            邮件接收者
 * @param title
 *            邮件的标题
 * @param content
 *            邮件的内容
 * @param sender
 *            邮件发送者
 * @param user
 *            发送者邮箱用户名
 * @param pwd
 *            发送者邮箱密码
 * @throws MessagingException 
 */
public static void sendEmail(String smtpHost, String receiver,
		String title, String content, String sender, String user, String pwd) throws MessagingException
		 {
	Properties props = new Properties();
	props.put("mail.host", smtpHost);
	props.put("mail.transport.protocol", "smtp");
	// props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动!
	props.put("mail.smtp.auth", "true");
	Session s = Session.getDefaultInstance(props);
	s.setDebug(true);
	MimeMessage message = new MimeMessage(s);
	// 给消息对象设置发件人/收件人/主题/发信时间
	// 发件人的邮箱
	InternetAddress from = new InternetAddress(sender);
	message.setFrom(from);
	InternetAddress to = new InternetAddress(receiver);
	message.setRecipient(Message.RecipientType.TO, to);
	message.setSubject(title);
	message.setSentDate(new Date());
	// 给消息对象设置内容
	BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
	mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
	Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
	// 象(事实上可以存放多个)
	mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
	message.setContent(mm);// 把mm作为消息对象的内容

	message.saveChanges();
	Transport transport = s.getTransport("smtp");
	transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的
	transport.sendMessage(message, message.getAllRecipients());
	transport.close();
}
 
Example 7
Source File: SendEMailVerifierExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);

    try {
        MailConfiguration configuration = createConfiguration(parameters);

        String timeoutVal = ConnectorOptions.extractOption(parameters, CONNECTION_TIMEOUT);
        if (ObjectHelper.isEmpty(timeoutVal)) {
            timeoutVal = Long.toString(DEFAULT_CONNECTION_TIMEOUT);
        }

        setConnectionTimeoutProperty(parameters, configuration, timeoutVal);

        JavaMailSender sender = createJavaMailSender(configuration);
        Session session = sender.getSession();

        Transport transport = session.getTransport(configuration.getProtocol());
        try {
            transport.connect(configuration.getHost(), configuration.getPort(),
                              configuration.getUsername(), configuration.getPassword());
        } finally {
            if (transport.isConnected()) {
                transport.close();
            }
        }
    } catch (Exception e) {
        ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
            .detail("mail_exception_message", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
            .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);

        builder.error(errorBuilder.build());
    }

    return builder.build();
}
 
Example 8
Source File: SendTextMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	Properties prop = new Properties();
	prop.setProperty("mail.debug", "true");
	prop.setProperty("mail.host", MAIL_SERVER_HOST);
	prop.setProperty("mail.transport.protocol", "smtp");
	prop.setProperty("mail.smtp.auth", "true");

	// 1、创建session
	Session session = Session.getInstance(prop);
	Transport ts = null;

	// 2、通过session得到transport对象
	ts = session.getTransport();

	// 3、连上邮件服务器
	ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);

	// 4、创建邮件
	MimeMessage message = new MimeMessage(session);

	// 邮件消息头
	message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
	message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
	message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
	message.setSubject("测试文本邮件"); // 邮件的标题

	// 邮件消息体
	message.setText("天下无双。");

	// 5、发送邮件
	ts.sendMessage(message, message.getAllRecipients());
	ts.close();
}
 
Example 9
Source File: JavaMailSenderImpl.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Obtain and connect a Transport from the underlying JavaMail Session,
 * passing in the specified host, port, username, and password.
 * @return the connected Transport object
 * @throws MessagingException if the connect attempt failed
 * @since 4.1.2
 * @see #getTransport
 * @see #getHost()
 * @see #getPort()
 * @see #getUsername()
 * @see #getPassword()
 */
protected Transport connectTransport() throws MessagingException {
	String username = getUsername();
	String password = getPassword();
	if ("".equals(username)) {  // probably from a placeholder
		username = null;
		if ("".equals(password)) {  // in conjunction with "" username, this means no password to use
			password = null;
		}
	}

	Transport transport = getTransport(getSession());
	transport.connect(getHost(), getPort(), username, password);
	return transport;
}
 
Example 10
Source File: MailUtil.java    From FreeServer with Apache License 2.0 5 votes vote down vote up
/**
 * 发送邮件
 * @param title 邮件标题
 * @param body  邮件正文
 */
public static void sendMaid(String title, String body){
    PropertiesUtil pro = new PropertiesUtil();
    Properties props = new Properties();
    props.setProperty("mail.smtp.auth", "true");
    props.setProperty("mail.smtp.ssl.enable", "true");
    props.setProperty("mail.smtp.connectiontimeout", "5000");
    try{
        //1、创建session
        Session session = Session.getInstance(props);
        //开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
        //session.setDebug(true);
        //2、通过session得到transport对象
        Transport ts = session.getTransport("smtp");
        //3、使用邮箱的用户名和密码连上邮件服务器,
        ts.connect(pro.getProperty("SERVER_HOST"), Integer.parseInt(pro.getProperty("SERVER_PORT")), pro.getProperty("SEND_USER"), pro.getProperty("PASSWORD"));
        //4、创建邮件
        MimeMessage message = new MimeMessage(session);
        //指明邮件的发件人
        message.setFrom(new InternetAddress(pro.getProperty("SEND_USER")));
        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(pro.getProperty("RECEIVE_USER")));
        //邮件的标题
        message.setSubject(title);
        //邮件的文本内容
        message.setContent(body, "text/html;charset=UTF-8");
        //5、发送邮件
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    } catch (Exception e){
        e.printStackTrace();
    }
}
 
Example 11
Source File: SendingMailService.java    From hellokoding-courses with MIT License 5 votes vote down vote up
private boolean sendMail(String toEmail, 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);
        session.setDebug(true);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mailProperties.getFrom(), mailProperties.getFromName()));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
        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 12
Source File: JavaMailSenderImpl.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Obtain and connect a Transport from the underlying JavaMail Session,
 * passing in the specified host, port, username, and password.
 * @return the connected Transport object
 * @throws MessagingException if the connect attempt failed
 * @since 4.1.2
 * @see #getTransport
 * @see #getHost()
 * @see #getPort()
 * @see #getUsername()
 * @see #getPassword()
 */
protected Transport connectTransport() throws MessagingException {
	String username = getUsername();
	String password = getPassword();
	if ("".equals(username)) {  // probably from a placeholder
		username = null;
		if ("".equals(password)) {  // in conjunction with "" username, this means no password to use
			password = null;
		}
	}

	Transport transport = getTransport(getSession());
	transport.connect(getHost(), getPort(), username, password);
	return transport;
}
 
Example 13
Source File: SmartSendMailUtil.java    From smart-admin with MIT License 5 votes vote down vote up
/**
 * 发送带附件的邮件
 *
 * @param sendMail 发件人邮箱
 * @param sendMailPwd 发件人密码
 * @param sendMailName 发件人昵称(可选)
 * @param receiveMail 收件人邮箱
 * @param receiveMailName 收件人昵称(可选)
 * @param sendSMTPHost 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同, 一般(只是一般, 绝非绝对)格式为: smtp.xxx.com
 * @param title 邮件主题
 * @param content 邮件正文
 * @author Administrator
 * @date 2017年12月13日 下午1:51:38
 */
public static void sendFileMail(String sendMail, String sendMailPwd, String sendMailName, String[] receiveMail, String receiveMailName, String sendSMTPHost, String title, String content,
                                InputStream is, String fileName, String port) {

    Session session = createSSLSession(sendSMTPHost, port, sendMailName, sendMailPwd);
    // 3. 创建一封邮件
    MimeMessage message;
    try {
        message = createMimeMessage(session, sendMail, sendMailName, receiveMail, receiveMailName, title, content);
        // 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
        MimeMultipart mm = new MimeMultipart();
        MimeBodyPart text = new MimeBodyPart();
        text.setContent(content, "text/html;charset=UTF-8");
        mm.addBodyPart(text);
        if (null != is && is.available() > 0) {
            MimeBodyPart attachment = new MimeBodyPart();
            DataSource source = new ByteArrayDataSource(is, "application/msexcel");
            // 将附件数据添加到"节点"
            attachment.setDataHandler(new DataHandler(source));
            // 设置附件的文件名(需要编码)
            attachment.setFileName(MimeUtility.encodeText(fileName));
            // 10. 设置文本和 附件 的关系(合成一个大的混合"节点" / Multipart )
            // 如果有多个附件,可以创建多个多次添加
            mm.addBodyPart(attachment);
        }
        message.setContent(mm);
        message.saveChanges();
        // 4. 根据 Session 获取邮件传输对象
        Transport transport = session.getTransport("smtp");
        transport.connect(sendSMTPHost, sendMail, sendMailPwd);
        //            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(message, message.getAllRecipients());
        // 7. 关闭连接
    } catch (Exception e) {
        log.error("", e);
    }

}
 
Example 14
Source File: RecoverController.java    From airsonic-advanced 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(Date.from(Instant.now()));

        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 15
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 16
Source File: MultipleMailExample.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);

	Transport transport = session.getTransport("smtp");
	transport.connect(testProps.getProperty("mail.smtp.host"),
			testProps.getProperty("mail.smtp.auth.user"),
			testProps.getProperty("mail.smtp.auth.password"));
	
	
	
	///////// 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"));

	for (int i=0; i<3; i++) {
		
		/* 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("multipleexample"+i+"@"+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: MultipleExample Testmessage "+i);
		msg.setText(TestUtil.bodyText);

		// send the message by JavaMail
		transport.sendMessage(msg, msg.getAllRecipients());
	}
	
	transport.close();
}
 
Example 17
Source File: SendMail.java    From PatatiumWebUi with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param userName  发送邮箱账号  [email protected]形式
 * @param passWord  发送邮件密码
 * @param smtpHost  stmp服务器地址
 * @param smtpPort  smtp服务器端口
 * @param from      发件人地址
 * @param tos       收件人地址
 * @param title     标题
 * @param content   内容
 */
public void sendmessage(String userName,String passWord,String smtpHost,String smtpPort,String from,String tos ,String title,String content)
{
	Properties smtpProper=setSmtp(smtpHost, smtpPort, userName, passWord);
	Auth authenticator=new Auth(userName, passWord);
	try {

		//创建session实例
		Session session=Session.getInstance(smtpProper, authenticator);
		MimeMessage message=new MimeMessage(session);
		session.setDebug(true);

		//设置from发件人邮箱地址
		message.setFrom(new InternetAddress(from));
		//收件人to LIST
		ArrayList<Address> toList=new ArrayList<Address>();
		//收件人字符串通过,号分隔收件人
		String[] toArray=tos.split(",");
		for (int i = 0; i < toArray.length; i++)
		{
			String str = toArray[i];
			toList.add(new InternetAddress(str));
		}
		//将收件人列表转换为收件人数组
		Address[] addresses=new Address[toList.size()];
		addresses=toList.toArray(addresses);
		//设置to收件人地址
		message.setRecipients(MimeMessage.RecipientType.TO,addresses);
		//设置邮件标题
		message.setSubject(title);
		//设置邮件内容
		message.setContent(content, "text/html;charset=UTF-8");
		//Transport.send(message);
		Transport transport=session.getTransport();
		transport.connect(smtpHost,userName, passWord);
		transport.sendMessage(message,addresses);
		log.info("发送邮件成功!");

	} catch (Exception e) {
		// TODO: handle exception
		log.error("发送邮件失败!");
		e.printStackTrace();
	}


}
 
Example 18
Source File: EmailUtils.java    From CodeDefenders with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sends an email to a given recipient for a given subject and content
 * with a {@code reply-to} header.
 *
 * @param to      The recipient of the mail ({@code to} header).
 * @param subject The subject of the mail.
 * @param text    The content of the mail.
 * @param replyTo The {@code reply-to} email header.
 * @return {@code true} if successful, {@code false} otherwise.
 */
private static boolean sendEmail(String to, String subject, String text, String replyTo) {
    final boolean emailEnabled = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAILS_ENABLED).getBoolValue();
    if (!emailEnabled) {
        logger.error("Tried to send a mail, but sending emails is disabled. Update your system settings.");
        return false;
    }

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

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

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

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

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

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

        logger.info(String.format("Mail sent: to: %s, replyTo: %s", to, replyTo));
    } catch (MessagingException messagingException) {
        logger.warn("Failed to send email.", messagingException);
        return false;
    }
    return true;
}
 
Example 19
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 20
Source File: MailUtil.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
 * 发送电子邮件
 * 
 * @param smtpHost
 *            发信主机
 * @param receiver
 *            邮件接收者
 * @param copy
 *            抄送列表
 * @param title
 *            邮件的标题
 * @param content
 *            邮件的内容
 * @param sender
 *            邮件发送者
 * @param user
 *            发送者邮箱用户名
 * @param pwd
 *            发送者邮箱密码
 * @throws Exception
 */
public static void sendEmail(String smtpHost, String receiver, String copy,
		String title, String content, String sender, String user, String pwd)
		throws Exception {
	Properties props = new Properties();
	props.put("mail.host", smtpHost);
	props.put("mail.transport.protocol", "smtp");
	// props.put("mail.smtp.host",smtpHost);//发信的主机,这里要把您的域名的SMTP指向正确的邮件服务器上,这里一般不要动!
	props.put("mail.smtp.auth", "true");
	Session s = Session.getDefaultInstance(props);
	s.setDebug(true);
	MimeMessage message = new MimeMessage(s);
	// 给消息对象设置发件人/收件人/主题/发信时间
	// 发件人的邮箱
	InternetAddress from = new InternetAddress(sender);
	message.setFrom(from);
	String[] receivers = receiver.split(",");
	InternetAddress[] to = new InternetAddress[receivers.length];
	for (int i = 0; i < receivers.length; i++) {
		to[i] = new InternetAddress(receivers[i]);
	}
	message.setRecipients(Message.RecipientType.TO, to);

	String[] copys = copy.split(",");
	InternetAddress[] cc = new InternetAddress[copys.length];
	for (int i = 0; i < copys.length; i++) {
		cc[i] = new InternetAddress(copys[i]);
	}
	message.setRecipients(Message.RecipientType.CC, cc);

	message.setSubject(title);
	message.setSentDate(new Date());
	// 给消息对象设置内容
	BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
	mdp.setContent(content, "text/html;charset=gb2312");// 给BodyPart对象设置内容和格式/编码方式防止邮件出现乱码
	Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
	// 象(事实上可以存放多个)
	mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
	message.setContent(mm);// 把mm作为消息对象的内容

	message.saveChanges();
	Transport transport = s.getTransport("smtp");
	transport.connect(smtpHost, user, pwd);// 设置发邮件的网关,发信的帐户和密码,这里修改为您自己用的
	transport.sendMessage(message, message.getAllRecipients());
	transport.close();
}