Java Code Examples for javax.mail.BodyPart#setContent()

The following examples show how to use javax.mail.BodyPart#setContent() . 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 lutece-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Send a calendar message.
 * 
 * @param mail
 *            The mail to send
 * @param transport
 *            the smtp transport object
 * @param session
 *            the smtp session object
 * @throws AddressException
 *             If invalid address
 * @throws SendFailedException
 *             If an error occurred during sending
 * @throws MessagingException
 *             If a messaging error occurred
 */
protected static void sendMessageCalendar( MailItem mail, Transport transport, Session session ) throws MessagingException
{
    Message msg = prepareMessage( mail, session );
    msg.setHeader( HEADER_NAME, HEADER_VALUE );

    MimeMultipart multipart = new MimeMultipart( );
    BodyPart msgBodyPart = new MimeBodyPart( );
    msgBodyPart.setDataHandler( new DataHandler( new ByteArrayDataSource( mail.getMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_HTML ) + AppPropertiesService.getProperty( PROPERTY_CHARSET ) ) ) );

    multipart.addBodyPart( msgBodyPart );

    BodyPart calendarBodyPart = new MimeBodyPart( );
    calendarBodyPart.setContent( mail.getCalendarMessage( ),
            AppPropertiesService.getProperty( PROPERTY_MAIL_TYPE_CALENDAR ) + AppPropertiesService.getProperty( PROPERTY_CHARSET )
                    + AppPropertiesService.getProperty( PROPERTY_CALENDAR_SEPARATOR )
                    + AppPropertiesService.getProperty( mail.getCreateEvent( ) ? PROPERTY_CALENDAR_METHOD_CREATE : PROPERTY_CALENDAR_METHOD_CANCEL ) );
    calendarBodyPart.addHeader( HEADER_NAME, CONSTANT_BASE64 );
    multipart.addBodyPart( calendarBodyPart );

    msg.setContent( multipart );

    sendMessage( msg, transport );
}
 
Example 2
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private static Multipart getMessagePart() throws MessagingException, IOException {
    Multipart multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(getVal("msg.Body"));
    multipart.addBodyPart(messageBodyPart);
    if (getBoolVal("attach.reports")) {
        LOG.info("Attaching Reports as zip");
        multipart.addBodyPart(getReportsBodyPart());
    } else {
        if (getBoolVal("attach.standaloneHtml")) {
            multipart.addBodyPart(getStandaloneHtmlBodyPart());
        }
        if (getBoolVal("attach.console")) {
            multipart.addBodyPart(getConsoleBodyPart());
        }
        if (getBoolVal("attach.screenshots")) {
            multipart.addBodyPart(getScreenShotsBodyPart());
        }
    }
    messageBodyPart.setContent(getVal("msg.Body")
            .concat("\n\n\n")
            .concat(MailComponent.getHTMLBody()), "text/html");
    return multipart;
}
 
Example 3
Source File: MailConnection.java    From scriptella-etl with Apache License 2.0 6 votes vote down vote up
protected MimeMessage format(Reader reader, PropertiesSubstitutor ps) throws MessagingException, IOException {
    //Read message body content
    String text = ps.substitute(reader);
    //Create message and set headers
    MimeMessage message = new MimeMessage(session);

    message.setFrom(InternetAddress.getLocalAddress(session));

    if (subject != null) {
        message.setSubject(ps.substitute(subject));
    }
    //if html content
    if (TYPE_HTML.equalsIgnoreCase(type)) {
        BodyPart body = new MimeBodyPart();
        body.setContent(text, "text/html");
        Multipart mp = new MimeMultipart("related");
        mp.addBodyPart(body);
        message.setContent(mp);
    } else {
        message.setText(text);
    }
    return message;
}
 
Example 4
Source File: MultiPartEmail.java    From commons-email with Apache License 2.0 6 votes vote down vote up
/**
 * Add a new part to the email.
 *
 * @param multipart The part to add.
 * @param index The index to add at.
 * @return The email.
 * @throws EmailException An error occurred while adding the part.
 * @since 1.0
 */
public Email addPart(final MimeMultipart multipart, final int index) throws EmailException
{
    final BodyPart bodyPart = createBodyPart();
    try
    {
        bodyPart.setContent(multipart);
        getContainer().addBodyPart(bodyPart, index);
    }
    catch (final MessagingException me)
    {
        throw new EmailException(me);
    }

    return this;
}
 
Example 5
Source File: DefaultMailSender.java    From Mario with Apache License 2.0 6 votes vote down vote up
private void sendAndCc(String from, String to, String copyto,
		String subject, String content) throws AddressException,
		MessagingException {
	props.put("mail.smtp.host", smtp);
	props.put("mail.smtp.auth", "true");
	mimeMessage.setSubject(subject);
	BodyPart bodyPart = new MimeBodyPart();
	bodyPart.setContent("" + content, "text/html;charset=GBK");
	multipart.addBodyPart(bodyPart);
	mimeMessage.setRecipients(Message.RecipientType.TO,
			InternetAddress.parse(to));
	mimeMessage.setRecipients(Message.RecipientType.CC,
			(Address[]) InternetAddress.parse(copyto));
	mimeMessage.setFrom(new InternetAddress(from));
	sendOut();
}
 
Example 6
Source File: MailServerImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public void sendHTML(Mailable email) throws MessagingException {
    Session mailSession = Session.getInstance(this.mailConfig, null);
    MimeMessage message = new MimeMessage(mailSession);
    MimeMultipart multipart = new MimeMultipart("alternative");
    BodyPart bp = new MimeBodyPart();
    bp.setContent(email.getMessage(), "text/plain; charset=UTF-8");
    BodyPart bp2 = new MimeBodyPart();
    bp2.setContent(email.getMessage(), "text/html; charset=UTF-8");
    
    multipart.addBodyPart(bp2);
    multipart.addBodyPart(bp);
    message.setContent(multipart);
    message.setSentDate(new java.util.Date());
    message.setFrom(new InternetAddress(email.getSender()));
    message.setSubject(email.getSubject());
    //FIXME if more than one recipient break it appart before setting the recipient field
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getRecipients()));
    Transport.send(message);
}
 
Example 7
Source File: MailUtil.java    From sdudoc with MIT License 5 votes vote down vote up
/** 发送用户验证的邮件 */
public static void sendAccountActiveEmail(User user) {

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

	// session.setDebug(true);

	String from = "[email protected]"; // 发邮件的出发地(发件人的信箱)
	Session session = getMailSession();
	// 定义message
	MimeMessage message = new MimeMessage(session);
	try {
		// 设定发送邮件的地址
		message.setFrom(new InternetAddress(from));
		// 设定接受邮件的地址
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
		// 设定邮件主题
		message.setSubject(subject);
		// 设定邮件内容
		BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
		mdp.setContent(content, "text/html;charset=utf8");// 给BodyPart对象设置内容和格式/编码方式
		Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
		// 象(事实上可以存放多个)
		mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
		message.setContent(mm);// 把mm作为消息对象的内容
		// message.setText(content);
		message.saveChanges();
		Transport.send(message);
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 8
Source File: Mailer.java    From hermes with Apache License 2.0 5 votes vote down vote up
/**
 * 添加超文本内容
 * 
 * @param html
 */
public void setHtml(String text) {
	try {
		Multipart multipart = new MimeMultipart();
		BodyPart html = new MimeBodyPart();
		html.setContent(text, "text/html; charset=utf-8");
		multipart.addBodyPart(html);
		message.setContent(multipart);
	} catch (MessagingException e) {
		throw new ServiceException("cannot set html.", "exception.mail.content", e);
	}
}
 
Example 9
Source File: MailSender.java    From iaf with Apache License 2.0 5 votes vote down vote up
private void setAttachments(MailSession mailSession, MimeMessage msg, String messageTypeWithCharset) throws MessagingException {
	List<MailAttachmentStream> attachmentList = mailSession.getAttachmentList();
	String message = mailSession.getMessage();
	if (attachmentList == null || attachmentList.size() == 0) {
		log.debug("no attachments found to attach to mailSession");
		msg.setContent(message, messageTypeWithCharset);
	} else {
		if(log.isDebugEnabled()) log.debug("found ["+attachmentList.size()+"] attachments to attach to mailSession");
		Multipart multipart = new MimeMultipart();
		BodyPart messagePart = new MimeBodyPart();
		messagePart.setContent(message, messageTypeWithCharset);
		multipart.addBodyPart(messagePart);

		int counter = 0;
		for (MailAttachmentStream attachment : attachmentList) {
			counter++;
			String name = attachment.getName();
			if (StringUtils.isEmpty(name)) {
				name = getDefaultAttachmentName() + counter;
			}
			log.debug("found attachment [" + attachment + "]");

			BodyPart messageBodyPart = new MimeBodyPart();
			messageBodyPart.setFileName(name);

			try {
				ByteArrayDataSource bads = new ByteArrayDataSource(attachment.getContent(), attachment.getMimeType());
				bads.setName(attachment.getName());
				messageBodyPart.setDataHandler(new DataHandler(bads));
			} catch (IOException e) {
				log.error("error attaching attachment to MailSession", e);
			}

			multipart.addBodyPart(messageBodyPart);
		}
		msg.setContent(multipart);
	}
}
 
Example 10
Source File: MimeMessageTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipartMessageChanges() throws Exception {

    MimeMessage mm = getMultipartMessage();

    MimeMultipart content1 = (MimeMultipart) mm.getContent();
    BodyPart b1 = content1.getBodyPart(0);
    b1.setContent("test€", "text/plain; charset=Cp1252");
    mm.setContent(content1, mm.getContentType());
    // .setHeader(RFC2822Headers.CONTENT_TYPE,contentType);
    mm.saveChanges();

    assertThat(getCleanedMessageSource(mm)).isEqualTo(getMultipartMessageExpected1());

    MimeMultipart content2 = (MimeMultipart) mm.getContent();
    content2.addBodyPart(new MimeBodyPart(new InternetHeaders(new ByteArrayInputStream(
            "Subject: test3\r\n".getBytes())), "third part".getBytes()));
    mm.setContent(content2, mm.getContentType());
    mm.saveChanges();

    assertThat(getCleanedMessageSource(mm)).isEqualTo(getMultipartMessageExpected2());

    mm.setContent("mynewcoòàùntent€à!", "text/plain; charset=cp1252");
    mm.setHeader(RFC2822Headers.CONTENT_TYPE, "binary/octet-stream");
    // mm.setHeader("Content-Transfer-Encoding","8bit");
    mm.saveChanges();

    assertThat(getCleanedMessageSource(mm)).isEqualTo(getMultipartMessageExpected3());

    LifecycleUtil.dispose(mm);

}
 
Example 11
Source File: AbstractMailSenderFactory.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 以HTML格式发送邮件.
 *
 * @param mailSender 待发送的邮件信息
 * @return Boolean
 */
protected boolean sendHtmlMail(final AbstractMailSender mailSender) {
    final Properties pro = mailSender.getProperties();
    MailAuthenticator authenticator = null;
    if (mailSender.isValidate()) {
        authenticator = new MailAuthenticator(mailSender.getUserName(), mailSender.getPassword());
    }

    final Session sendMailSession;
    if(singletonSessionInstance) {
        sendMailSession = Session.getDefaultInstance(pro, authenticator);
    } else {
        sendMailSession = Session.getInstance(pro, authenticator);
    }
    
    sendMailSession.setDebug(debugEnabled);
    try {
        final Message mailMessage = new MimeMessage(sendMailSession);
        final Address from = new InternetAddress(mailSender.getFromAddress());
        mailMessage.setFrom(from);
        mailMessage.setRecipients(Message.RecipientType.TO, toAddresses(mailSender.getToAddress()));
        mailMessage.setSubject(mailSender.getSubject());
        mailMessage.setSentDate(new Date());
        final Multipart mainPart = new MimeMultipart();
        final BodyPart html = new MimeBodyPart();
        html.setContent(mailSender.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
        return true;
    } catch (final MessagingException ex) {
        LOGGER.error(ex.getMessage(), ex);
    }
    
    return false;
}
 
Example 12
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 13
Source File: MailHandler.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
protected MimeMessage appendIcsBody(MimeMessage msg, MailMessage m) throws Exception {
	log.debug("setMessageBody for iCal message");
	// -- Create a new message --
	Multipart multipart = new MimeMultipart();

	Multipart multiBody = new MimeMultipart("alternative");
	BodyPart html = new MimeBodyPart();
	html.setDataHandler(new DataHandler(new ByteArrayDataSource(m.getBody(), "text/html; charset=UTF-8")));
	multiBody.addBodyPart(html);

	BodyPart iCalContent = new MimeBodyPart();
	iCalContent.addHeader("content-class", "urn:content-classes:calendarmessage");
	iCalContent.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
			"text/calendar; charset=UTF-8; method=REQUEST")));
	multiBody.addBodyPart(iCalContent);
	BodyPart body = new MimeBodyPart();
	body.setContent(multiBody);
	multipart.addBodyPart(body);

	BodyPart iCalAttachment = new MimeBodyPart();
	iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
			"application/ics")));
	iCalAttachment.removeHeader("Content-Transfer-Encoding");
	iCalAttachment.addHeader("Content-Transfer-Encoding", "base64");
	iCalAttachment.removeHeader("Content-Type");
	iCalAttachment.addHeader("Content-Type", "application/ics");
	iCalAttachment.setFileName("invite.ics");
	multipart.addBodyPart(iCalAttachment);

	msg.setContent(multipart);
	return msg;
}
 
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: TestMailClient.java    From holdmail with Apache License 2.0 4 votes vote down vote up
private BodyPart createHtmlBodyPart(String htmlMessageBody) throws MessagingException {
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(htmlMessageBody, "text/html");
    return htmlPart;

}
 
Example 16
Source File: SimpleMailSender.java    From KJFrameForAndroid with Apache License 2.0 4 votes vote down vote up
/**
 * 以HTML格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件信息
 */
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    // 如果需要身份认证,则创建一个密码验证器
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(),
                mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session
            .getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
 
Example 17
Source File: MailManager.java    From Cynthia with GNU General Public License v2.0 4 votes vote down vote up
/**
	 * @description:send mail
	 * @date:2014-5-6 下午12:11:34
	 * @version:v1.0
	 * @param subject:mail subject
	 * @param recievers:mail recievers
	 * @param content:mail content
	 * @return:if mail send success
	 */
	public static boolean sendMail(String fromUser, String subject,String[] recievers,String content){
        try{
            Properties props = ConfigManager.getEmailProperties();
            
            //配置中定义不发送邮件
            if (props.getProperty("mail.enable") == null || !props.getProperty("mail.enable").equals("true")) {
				System.out.println("there is a mail not send by config!");
            	return true;
			}
            
            //创建一个程序与邮件服务器的通信
            Session mailConnection = Session.getInstance(props,null);
            Message msg = new MimeMessage(mailConnection);
                                
            //设置发送人和接受人
            Address sender = new InternetAddress(props.getProperty("mail.user"));
            //单个接收人
            //Address receiver = new InternetAddress("[email protected]");
            //多个接收人
            StringBuffer buffer = new StringBuffer();
            for (String reciever : recievers) {
				buffer.append(buffer.length() > 0 ? ",":"").append(reciever);
			}
            String all = buffer.toString();
            System.out.println("send Mail,mailList:" + all);
            
            msg.setFrom(sender);
            Set<InternetAddress> toUserSet = new HashSet<InternetAddress>();
            //邮箱有效性较验
            for (int i = 0; i < recievers.length; i++) {
                if(recievers[i].trim().matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)+$")){
                	toUserSet.add(new InternetAddress(recievers[i].trim()));
                }
            }
            
            msg.setRecipients(Message.RecipientType.TO, toUserSet.toArray(new InternetAddress[0]));
            
            //设置邮件主题
            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));   //中文乱码问题
            
            //设置邮件内容
            BodyPart messageBodyPart = new MimeBodyPart(); 
            messageBodyPart.setContent( content, "text/html; charset=utf-8" ); // 中文
            Multipart multipart = new MimeMultipart(); 
            multipart.addBodyPart( messageBodyPart ); 
            msg.setContent(multipart);
                                
            /**********************发送附件************************/
//	            //新建一个MimeMultipart对象用来存放多个BodyPart对象
//	            Multipart mtp=new MimeMultipart();
//	            //------设置信件文本内容------
//	            //新建一个存放信件内容的BodyPart对象
//	            BodyPart mdp=new MimeBodyPart();
//	            //给BodyPart对象设置内容和格式/编码方式
//	            mdp.setContent("hello","text/html;charset=gb2312");
//	            //将含有信件内容的BodyPart加入到MimeMultipart对象中
//	            mtp.addBodyPart(mdp);
//	                                
//	            //设置信件的附件(用本地机上的文件作为附件)
//	            mdp=new MimeBodyPart();
//	            FileDataSource fds=new FileDataSource("f:/webservice.doc");
//	            DataHandler dh=new DataHandler(fds);
//	            mdp.setFileName("webservice.doc");//可以和原文件名不一致
//	            mdp.setDataHandler(dh);
//	            mtp.addBodyPart(mdp);
//	            //把mtp作为消息对象的内容
//	            msg.setContent(mtp);
           /**********************发送附件结束************************/  

            //先进行存储邮件
            msg.saveChanges();
            Transport trans = mailConnection.getTransport(props.getProperty("mail.protocal"));
            //邮件服务器名,用户名,密码
            trans.connect(props.getProperty("mail.smtp.host"), props.getProperty("mail.user"),  props.getProperty("mail.pass"));
            trans.sendMessage(msg, msg.getAllRecipients());
            
            //关闭通道
            if (trans.isConnected()) {
            	trans.close();
			}
            return true;
        }catch(Exception e)
        {
            System.err.println(e);
            return false;
        }
        finally{
        }
	}
 
Example 18
Source File: MailDaemon.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * sends invitation
 * 
 * @param session     session connection to the SMTP server
 * @param toemails    list of recipient e-mails
 * @param subject     invitation subject
 * @param body        invitation start
 * @param fromemail   user sending the invitation
 * @param startdate   start date of the invitation
 * @param enddate     end date of the invitation
 * @param location    location of the invitation
 * @param uid         unique id
 * @param cancelation true if this is a cancelation
 */
private void sendInvitation(Session session, String[] toemails, String subject, String body, String fromemail,
		Date startdate, Date enddate, String location, String uid, boolean cancelation) {
	try {
		// prepare mail mime message
		MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap();
		mimetypes.addMimeTypes("text/calendar ics ICS");
		// register the handling of text/calendar mime type
		MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
		mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");

		MimeMessage msg = new MimeMessage(session);
		// set message headers

		msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
		msg.addHeader("format", "flowed");
		msg.addHeader("Content-Transfer-Encoding", "8bit");
		InternetAddress fromemailaddress = new InternetAddress(fromemail);
		msg.setFrom(fromemailaddress);
		msg.setReplyTo(InternetAddress.parse(fromemail, false));
		msg.setSubject(subject, "UTF-8");
		msg.setSentDate(new Date());

		// set recipient

		InternetAddress[] recipients = new InternetAddress[toemails.length + 1];

		String attendeesinvcalendar = "";
		for (int i = 0; i < toemails.length; i++) {
			recipients[i] = new InternetAddress(toemails[i]);
			attendeesinvcalendar += "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:"
					+ toemails[i] + "\n";
		}

		recipients[toemails.length] = fromemailaddress;
		msg.setRecipients(Message.RecipientType.TO, recipients);

		Multipart multipart = new MimeMultipart("alternative");
		// set body
		MimeBodyPart descriptionPart = new MimeBodyPart();
		descriptionPart.setContent(body, "text/html; charset=utf-8");
		multipart.addBodyPart(descriptionPart);

		// set invitation
		BodyPart calendarPart = new MimeBodyPart();

		String method = "METHOD:REQUEST\n";
		if (cancelation)
			method = "METHOD:CANCEL\n";

		String calendarContent = "BEGIN:VCALENDAR\n" + method + "PRODID: BCP - Meeting\n" + "VERSION:2.0\n"
				+ "BEGIN:VEVENT\n" + "DTSTAMP:" + iCalendarDateFormat.format(new Date()) + "\n" + "DTSTART:"
				+ iCalendarDateFormat.format(startdate) + "\n" + "DTEND:" + iCalendarDateFormat.format(enddate)
				+ "\n" + "SUMMARY:" + subject + "\n" + "UID:" + uid + "\n" + attendeesinvcalendar
				+ "ORGANIZER:MAILTO:" + fromemail + "\n" + "LOCATION:" + location + "\n" + "DESCRIPTION:" + subject
				+ "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n"
				+ "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n"
				+ "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR";

		calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage");
		calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL");
		multipart.addBodyPart(calendarPart);
		msg.setContent(multipart);
		logger.severe("Invitation is ready");
		Transport.send(msg);

		logger.severe("EMail Invitation Sent Successfully!! to " + attendeesinvcalendar);
	} catch (Exception e) {
		logger.severe(
				"--- Exception in sending invitation --- " + e.getClass().toString() + " - " + e.getMessage());
		if (e.getCause() != null)
			logger.severe(" cause  " + e.getCause().getClass().toString() + " - " + e.getCause().getMessage());
		throw new RuntimeException("email sending error " + e.getMessage() + " for server = server:"
				+ this.smtpserver + " - port:" + this.port + " - user:" + this.user);
	}

}
 
Example 19
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();
}
 
Example 20
Source File: SimpleMailSender.java    From disconf with Apache License 2.0 3 votes vote down vote up
/**
 * 以HTML格式发送邮件
 *
 * @param mailInfo 待发送的邮件信息
 */
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {

    try {

        LOG.info("send to " + mailInfo.getFromAddress());

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

        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();

        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();

        // 设置HTML内容
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);

        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);

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

        LOG.info("send to " + mailInfo.getFromAddress() + " dnoe.");

        return true;

    } catch (MessagingException ex) {

        LOG.error(ex.toString(), ex);
    }
    return false;
}