当前位置: 首页>>代码示例>>Java>>正文


Java Message.setContent方法代码示例

本文整理汇总了Java中javax.mail.Message.setContent方法的典型用法代码示例。如果您正苦于以下问题:Java Message.setContent方法的具体用法?Java Message.setContent怎么用?Java Message.setContent使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.mail.Message的用法示例。


在下文中一共展示了Message.setContent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: sendMsg

import javax.mail.Message; //导入方法依赖的package包/类
public boolean sendMsg(String recipient, String subject, String content)
		throws MessagingException {
	// Create a mail object
	Session session = Session.getInstance(props, new Authenticator() {
		// Set the account information session,transport will send mail
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(Constants.MAIL_USERNAME, Constants.MAIL_PASSWORD);
		}
	});
	session.setDebug(true);
	Message msg = new MimeMessage(session);
	try {
		msg.setSubject(subject);			//Set the mail subject
		msg.setContent(content,"text/html;charset=utf-8");
		msg.setFrom(new InternetAddress(Constants.MAIL_USERNAME));			//Set the sender
		msg.setRecipient(RecipientType.TO, new InternetAddress(recipient));	//Set the recipient
		Transport.send(msg);
		return true;
	} catch (Exception ex) {
		ex.printStackTrace();
		System.out.println(ex.getMessage());
		return false;
	}

}
 
开发者ID:ICT-BDA,项目名称:EasyML,代码行数:27,代码来源:JavaMail.java

示例2: sendAttachMail

import javax.mail.Message; //导入方法依赖的package包/类
public boolean sendAttachMail(MailSenderInfo mailInfo) {
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailInfo.getToAddress()));
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());
        Multipart multi = new MimeMultipart();
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        multi.addBodyPart(textBodyPart);
        for (String path : mailInfo.getAttachFileNames()) {
            DataSource fds = new FileDataSource(path);
            BodyPart fileBodyPart = new MimeBodyPart();
            fileBodyPart.setDataHandler(new DataHandler(fds));
            fileBodyPart.setFileName(path.substring(path.lastIndexOf("/") + 1));
            multi.addBodyPart(fileBodyPart);
        }
        mailMessage.setContent(multi);
        mailMessage.saveChanges();
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
 
开发者ID:JamesLiAndroid,项目名称:AndroidKillerService,代码行数:33,代码来源:SimpleMailSender.java

示例3: createMessage

import javax.mail.Message; //导入方法依赖的package包/类
private static Message createMessage(Session session)
        throws MessagingException, IOException {
    Message msg = new MimeMessage(session);
    InternetAddress fromAddress = new InternetAddress(
            getVal("from.mail"), getVal("username"));
    msg.setFrom(fromAddress);
    Optional.ofNullable(getVal("to.mail")).ifPresent((String tos) -> {
        for (String to : tos.split(";")) {
            try {
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
                        to, to));
            } catch (Exception ex) {
                Logger.getLogger(Mailer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    msg.setSubject(parseSubject(getVal("msg.subject")));
    msg.setContent(getMessagePart());
    return msg;
}
 
开发者ID:CognizantQAHub,项目名称:Cognizant-Intelligent-Test-Scripter,代码行数:22,代码来源:Mailer.java

示例4: sendHtmlMail

import javax.mail.Message; //导入方法依赖的package包/类
public boolean sendHtmlMail(MailSenderInfo mailInfo) {
    XLog.d("发送网页版邮件!");
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    try {
        Message mailMessage = new MimeMessage(Session.getInstance(pro, authenticator));
        mailMessage.setFrom(new InternetAddress(mailInfo.getFromAddress()));
        String[] receivers = mailInfo.getReceivers();
        Address[] tos = new InternetAddress[receivers.length];
        for (int i = 0; i < receivers.length; i++) {
            tos[i] = new InternetAddress(receivers[i]);
        }
        mailMessage.setRecipients(Message.RecipientType.TO, tos);
        mailMessage.setSubject(mailInfo.getSubject());
        mailMessage.setSentDate(new Date());

        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        mailMessage.setContent(mainPart);
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
        return false;
    }
}
 
开发者ID:JamesLiAndroid,项目名称:AndroidKillerService,代码行数:32,代码来源:SimpleMailSender.java

示例5: sendMail

import javax.mail.Message; //导入方法依赖的package包/类
/**
 * 发邮件处理
 * 
 * @param toAddr
 *            邮件地址
 * @param content
 *            邮件内容
 * @return 成功标识
 */
public static boolean sendMail(String toAddr, String title, String content, boolean isHtmlFormat) {

    final String username = YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_USERNAME);
    final String password = YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_PASSWORD);

    Properties props = new Properties();
    props.put("mail.smtp.auth", YiDuConstants.yiduConf.getBoolean(YiDuConfig.MAIL_SMTP_AUTH, true));
    props.put("mail.smtp.starttls.enable",
            YiDuConstants.yiduConf.getBoolean(YiDuConfig.MAIL_SMTP_STARTTLS_ENABLE, true));
    props.put("mail.smtp.host", YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_HOST));
    props.put("mail.smtp.port", YiDuConstants.yiduConf.getInt(YiDuConfig.MAIL_SMTP_PORT, 25));

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

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(YiDuConstants.yiduConf.getString(YiDuConfig.MAIL_SMTP_FROM)));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddr));
        message.setSubject(title);
        if (isHtmlFormat) {
            message.setContent(content, "text/html");
        } else {
            message.setText(content);
        }
        Transport.send(message);

    } catch (MessagingException e) {
        logger.warn(e);
        return false;
    }
    return true;

}
 
开发者ID:luckyyeah,项目名称:YiDu-Novel,代码行数:47,代码来源:MailUtils.java

示例6: sendEmail

import javax.mail.Message; //导入方法依赖的package包/类
public static void sendEmail(String host, String port,
        final String userName, final String password, String toAddress,
        String subject, String message, String nombreArchivoAdj, String urlArchivoAdj)
        		throws AddressException, MessagingException {
 
    // sets SMTP server properties
    Properties properties = new Properties();
    properties.put("mail.smtp.host", host);
    properties.put("mail.smtp.port", port);
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.starttls.enable", "true");
 
    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    };
 
    Session session = Session.getInstance(properties, auth);

    //Se crea la parte del cuerpo del mensaje.
    BodyPart texto = new MimeBodyPart();
    texto.setText(message);        
    BodyPart adjunto = new MimeBodyPart();
    
    if(nombreArchivoAdj != null ){	        
     adjunto.setDataHandler(new DataHandler(new FileDataSource(urlArchivoAdj)));
     adjunto.setFileName(nombreArchivoAdj);
    }
    
    //Juntar las dos partes
    MimeMultipart multiParte = new MimeMultipart();
    multiParte.addBodyPart(texto);
    if (nombreArchivoAdj != null) multiParte.addBodyPart(adjunto);
    
    // creates a new e-mail message
    Message msg = new MimeMessage(session);
 
    msg.setFrom(new InternetAddress(userName));
    InternetAddress[] toAddresses = null;
    toAddresses = InternetAddress.parse(toAddress, false);

    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    msg.setSubject(subject);
    msg.setSentDate(new Date());
    //msg.setText(message);
    msg.setContent(multiParte);
 
    // sends the e-mail
    Transport.send(msg);       

}
 
开发者ID:stppy,项目名称:spr,代码行数:54,代码来源:SendMail.java

示例7: _setupMessage

import javax.mail.Message; //导入方法依赖的package包/类
/**
 * Set up a new message.
 */
private Message _setupMessage(Message msg)
{
  try
  {
    String username = _account.getUsername();
    String from = username + "@" + _account.getDomain();
    List<InternetAddress> to = _getEmailList(getTo());
    
    List<InternetAddress> cc = null;
    String ccString = getCc();
    if(ccString != null) 
    {
      cc = _getEmailList(ccString);  
    }
    
    msg.setFrom(new InternetAddress(from));
    if ((to != null) && !to.isEmpty())
      msg.setRecipients(Message.RecipientType.TO,
                        to.toArray(new InternetAddress[0]));

    if ((cc != null) && !cc.isEmpty())
      msg.setRecipients(Message.RecipientType.CC,
                        cc.toArray(new InternetAddress[0]));
    msg.setSubject(_subject == null ? "" : _subject);
    if ((_attachment1 == null) &&
        (_attachment2 == null) &&
        (_attachment3 == null))
    {
      msg.setText(_content == null ? "" : _content);
    }
    // Multipart.
    else
    {
      // Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();

      // Fill the message
      messageBodyPart.setText(_content == null ? "" : _content);

      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(messageBodyPart);

      if (_attachment1 != null)
        _addAttachment(multipart, _attachment1);
      if (_attachment2 != null)
        _addAttachment(multipart, _attachment2);
      if (_attachment3 != null)
        _addAttachment(multipart, _attachment3);

      // Put all the parts in the message
      msg.setContent(multipart);
    }

    String mailer = "OracleAdfEmailDemo";
    msg.setHeader("X-Mailer", mailer);
    msg.setSentDate(new Date());

    return msg;
  }
  catch(AddressException ae)
  {
     _showSendException(ae);
  }
  catch(MessagingException me)
  {
    _showSendException(me);
  }
  catch(Exception e)
  {
    _showSendException(e);
  }

  return null;
}
 
开发者ID:apache,项目名称:myfaces-trinidad,代码行数:78,代码来源:NewMessageBackingBean.java

示例8: sendHtmlMail

import javax.mail.Message; //导入方法依赖的package包/类
/**
 * 以HTML格式发送邮件
 * 
 * @param mailInfo
 *            待发送的邮件信息
 */
public boolean sendHtmlMail(MailSenderObj 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);
	sendMailSession.setDebug(true);// 设置debug模式 在控制台看到交互信息
	try {
		// 根据session创建一个邮件消息
		Message mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		Address from = new InternetAddress(mailInfo.getFromAddress());
		// 设置邮件消息的发送者
		mailMessage.setFrom(from);
		// 创建邮件的接收者地址,并设置到邮件消息中
		String[] asToAddr = mailInfo.getToAddress();
		if (asToAddr == null) {
			logger.debug("邮件发送失败,收信列表为空" + mailInfo);
			return false;
		}
		for (int i=0; i<asToAddr.length; i++) {
			if (asToAddr[i] == null || asToAddr[i].equals("")) {
				continue;
			}
			Address to = new InternetAddress(asToAddr[i]);
			// Message.RecipientType.TO属性表示接收者的类型为TO
			mailMessage.addRecipient(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);
		logger.info("发送邮件成功。" + mailInfo);
		return true;
	} catch (MessagingException ex) {
		logger.error("发送邮件失败:" + ex.getMessage() + Arrays.toString(ex.getStackTrace()));
	}
	return false;
}
 
开发者ID:langxianwei,项目名称:iot-plat,代码行数:61,代码来源:SimpleMailSender.java

示例9: sendTextEmail

import javax.mail.Message; //导入方法依赖的package包/类
public static void sendTextEmail(String recvEmail) {
	try { 
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.qq.com");
		props.setProperty("mail.smtp.auth", "true");
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.socketFactory.port",  "994");
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("463112653", "manllfvunnfwbjhh");
			}
		});
		session.setDebug(true);
		Message msg = new MimeMessage(session);
		msg.setSubject("Hello Vme");
		//整个邮件的MultiPart(不能直接加入内容,需要在bodyPart中加入)
		Multipart emailPart = new MimeMultipart();
		MimeBodyPart attr1 = new MimeBodyPart();
		attr1.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/2601169057.png")));
		attr1.setFileName("tip.pic");
		
		MimeBodyPart attr2 = new MimeBodyPart();
		attr2.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/1724836491.png")));
		attr2.setFileName(MimeUtility.encodeText("哦图像"));
		
		MimeBodyPart content = new MimeBodyPart();
		MimeMultipart contentPart = new MimeMultipart();
		
		MimeBodyPart imgPart = new MimeBodyPart();
		imgPart.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/1724836491.png")));
		imgPart.setContentID("pic");
		
		MimeBodyPart htmlPart = new MimeBodyPart();
		htmlPart.setContent("<h1><a href='www.baidu.com'>百度一下</a><img src='cid:pic'/></h1>", "text/html;charset=utf-8");
		
		contentPart.addBodyPart(imgPart);
		contentPart.addBodyPart(htmlPart);
		content.setContent(contentPart);
		
		emailPart.addBodyPart(attr1);
		emailPart.addBodyPart(attr2);
		emailPart.addBodyPart(content);
		msg.setContent(emailPart);
		
		msg.setFrom(new InternetAddress("[email protected]"));
		msg.setRecipients(RecipientType.TO, InternetAddress.parse("260[email protected],[email protected]"));
		msg.setRecipients(RecipientType.CC, InternetAddress.parse("[email protected],[email protected]"));
		Transport.send(msg);
	} catch (Exception e) {
		e.printStackTrace();
	} 
}
 
开发者ID:Fetax,项目名称:Fetax-AI,代码行数:55,代码来源:EmailHelper.java

示例10: sendMail

import javax.mail.Message; //导入方法依赖的package包/类
public void sendMail(int uID, String URLlink, String Uname, String mailuser, String mailpass, String mailserver, String mailport, String mailsendadd, DB dbProperties) {
	
	Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailserver);
    props.put("mail.smtp.port", mailport);

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailsendadd));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(ForgotDao.getEmail(uID, dbProperties)));
        message.setSubject("Forgot your password!");
        message.setContent("Dear "+Uname+", <BR><BR> Please click the following link to gain access to your account. <BR><BR> <a href=\""+URLlink+"\">Activate Account</a> <BR><BR> Thank You,", "text/html; charset=utf-8");
       
        Transport.send(message);

        System.out.println("Forgot Password E-mail Sent - "+ForgotDao.getEmail(uID, dbProperties));

    } catch (MessagingException e) {
        
        System.out.println("Error - Forgot Password E-mail Send FAILED - "+ForgotDao.getEmail(uID, dbProperties));
        throw new RuntimeException(e);
    }	
}
 
开发者ID:CanadianRepublican,项目名称:DDNS_Server,代码行数:35,代码来源:ForgotServlet.java

示例11: sendMail

import javax.mail.Message; //导入方法依赖的package包/类
public void sendMail(String uEmail, String URLlink, String Uname, String mailuser, String mailpass, String mailserver, String mailport, String mailsendadd) {
	
	Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", mailserver);
    props.put("mail.smtp.port", mailport);

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

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(mailsendadd));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(uEmail));
        message.setSubject("Activate your account!!!");
        message.setContent("Dear "+Uname+", <BR><BR> Please click the following link to activate your account. <BR><BR> <a href=\""+URLlink+"\">Activate Account</a> <BR><BR> Thank You,", "text/html; charset=utf-8");
       
        Transport.send(message);

        System.out.println("Create Account E-mail Sent");

    } catch (MessagingException e) {
        
        System.out.println("Error - Create Account E-mail Send FAILED");
        throw new RuntimeException(e);
    }
}
 
开发者ID:CanadianRepublican,项目名称:DDNS_Server,代码行数:35,代码来源:CreateServlet.java

示例12: sendAlert

import javax.mail.Message; //导入方法依赖的package包/类
@Override
public void sendAlert(Observable observable) throws AddressException, MessagingException {
	if (observable instanceof AbstarctMower) {
		AbstarctMower mower = (AbstarctMower) observable;
		ArrayList<MowerPosition> positionHistory = mower.getPositionHistory();
		SettingInterface settingLoader = SettingLoaderFactory.getSettingLoader(DEFAULT);
		Properties props = new Properties();
		props.put("mail.smtp.host", settingLoader.getSMTPServer());
		props.put("mail.smtp.socketFactory.port", String.valueOf(settingLoader.getSMTPPort()));
		props.put("mail.smtp.socketFactory.class", settingLoader.getSSLSocketFactory());
		props.put("mail.smtp.auth", settingLoader.isAuthenticationRequired());
		props.put("mail.smtp.port", String.valueOf(settingLoader.getSMTPPort()));

		String password = PasswordDecrypt.getInstance().decrypt("HA%HYDG1;[email protected]", "84m6BrC?T^P*!#bz",
				settingLoader.getPassword());

		Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(settingLoader.getUserName(), password);
			}
		});

		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress(settingLoader.getSender()));
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(settingLoader.getUserName()));

		String key0 = mower.getIdentifier();

		String subject = MessageGetter.getMessage(EMAIL_ALERT_SUBJECT, new String[] { key0 });

		message.setSubject(subject);
		StringBuilder body = new StringBuilder();

		for (int i = 1; i < positionHistory.size(); i++) {
			MowerPosition mowerPosition = positionHistory.get(i);
			body.append(mowerPosition.toString()).append(BR).append(BR);
		}
		String key1 = mower.getUpdateDate() != null ? mower.getUpdateDate().toString() : N_A;
		String key2 = positionHistory.get(0) != null ? positionHistory.get(0).toString() : N_A;
		String key3 = body.toString();

		String bodyMessage = MessageGetter.getMessage(EMAIL_ALERT_MESSAGE, new String[] { key0, key1, key2, key3 });

		message.setContent(bodyMessage, CONTENT_TYPE);
		Transport.send(message);
	}
}
 
开发者ID:camy2408,项目名称:automatic-mower,代码行数:48,代码来源:MowerStatusChangedEmailAlert.java

示例13: doPost

import javax.mail.Message; //导入方法依赖的package包/类
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
    throws IOException, ServletException
{

    // Acquire request parameters we need
    String from = request.getParameter("mailfrom");
    String to = request.getParameter("mailto");
    String subject = request.getParameter("mailsubject");
    String content = request.getParameter("mailcontent");
    if ((from == null) || (to == null) ||
        (subject == null) || (content == null)) {
        RequestDispatcher rd =
            getServletContext().getRequestDispatcher("/jsp/mail/sendmail.jsp");
        rd.forward(request, response);
        return;
    }

    // Prepare the beginning of our response
    PrintWriter writer = response.getWriter();
    response.setContentType("text/html");
    writer.println("<html>");
    writer.println("<head>");
    writer.println("<title>Example Mail Sending Results</title>");
    writer.println("</head>");
    writer.println("<body bgcolor=\"white\">");

    try {

        // Acquire our JavaMail session object
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        Session session = (Session) envCtx.lookup("mail/Session");

        // Prepare our mail message
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        InternetAddress dests[] = new InternetAddress[]
            { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, dests);
        message.setSubject(subject);
        message.setContent(content, "text/plain");

        // Send our mail message
        Transport.send(message);

        // Report success
        writer.println("<strong>Message successfully sent!</strong>");

    } catch (Throwable t) {

        writer.println("<font color=\"red\">");
        writer.print("ENCOUNTERED EXCEPTION:  ");
        writer.println(HTMLFilter.filter(t.toString()));
        writer.println("<pre>");
        StringWriter trace = new StringWriter();
        t.printStackTrace(new PrintWriter(trace));
        writer.print(HTMLFilter.filter(trace.toString()));
        writer.println("</pre>");
        writer.println("</font>");

    }

    // Prepare the ending of our response
    writer.println("<br><br>");
    writer.println("<a href=\"jsp/mail/sendmail.jsp\">Create a new message</a><br>");
    writer.println("<a href=\"jsp/index.html\">Back to examples home</a><br>");
    writer.println("</body>");
    writer.println("</html>");        

}
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:72,代码来源:SendMailServlet.java

示例14: doPost

import javax.mail.Message; //导入方法依赖的package包/类
public void doPost(HttpServletRequest request,
                   HttpServletResponse response)
    throws IOException, ServletException
{

    // Acquire request parameters we need
    String from = request.getParameter("mailfrom");
    String to = request.getParameter("mailto");
    String subject = request.getParameter("mailsubject");
    String content = request.getParameter("mailcontent");
    if ((from == null) || (to == null) ||
        (subject == null) || (content == null)) {
        RequestDispatcher rd =
            getServletContext().getRequestDispatcher("/jsp/mail/sendmail.jsp");
        rd.forward(request, response);
        return;
    }

    // Prepare the beginning of our response
    PrintWriter writer = response.getWriter();
    response.setContentType("text/html");
    writer.println("<html>");
    writer.println("<head>");
    writer.println("<title>Example Mail Sending Results</title>");
    writer.println("</head>");
    writer.println("<body bgcolor=\"white\">");

    try {

        // Acquire our JavaMail session object
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        Session session = (Session) envCtx.lookup("mail/Session");

        // Prepare our mail message
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        InternetAddress dests[] = new InternetAddress[]
            { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, dests);
        message.setSubject(subject);
        message.setContent(content, "text/plain");

        // Send our mail message
        Transport.send(message);

        // Report success
        writer.println("<strong>Message successfully sent!</strong>");

    } catch (Throwable t) {

        writer.println("<font color=\"red\">");
        writer.println("ENCOUNTERED EXCEPTION:  " + t);
        writer.println("<pre>");
        t.printStackTrace(writer);
        writer.println("</pre>");
        writer.println("</font>");

    }

    // Prepare the ending of our response
    writer.println("<br><br>");
    writer.println("<a href=\"jsp/mail/sendmail.jsp\">Create a new message</a><br>");
    writer.println("<a href=\"jsp/index.html\">Back to examples home</a><br>");
    writer.println("</body>");
    writer.println("</html>");        

}
 
开发者ID:parabuild-ci,项目名称:parabuild-ci,代码行数:69,代码来源:SendMailServlet.java

示例15: sendTextEmail

import javax.mail.Message; //导入方法依赖的package包/类
public static void sendTextEmail(String recvEmail) {
	try { 
		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "smtp");
		props.setProperty("mail.host", "smtp.qq.com");
		props.setProperty("mail.smtp.auth", "true");
		props.put("mail.smtp.ssl.enable", "true");
		props.put("mail.smtp.socketFactory.port",  "994");
		Session session = Session.getInstance(props, new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("463112653", "manllfvunnfwbjhh");
			}
		});
		session.setDebug(true);
		Message msg = new MimeMessage(session);
		msg.setSubject("Hello Vme");
		//整个邮件的MultiPart(不能直接加入内容,需要在bodyPart中加入)
		Multipart emailPart = new MimeMultipart();
		MimeBodyPart attr1 = new MimeBodyPart();
		attr1.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/2601169057.png")));
		attr1.setFileName("tip.pic");
		
		MimeBodyPart attr2 = new MimeBodyPart();
		attr2.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/1724836491.png")));
		attr2.setFileName(MimeUtility.encodeText("哦图像"));
		
		MimeBodyPart content = new MimeBodyPart();
		MimeMultipart contentPart = new MimeMultipart();
		
		MimeBodyPart imgPart = new MimeBodyPart();
		imgPart.setDataHandler(new DataHandler(new FileDataSource("E:/workspaces/Archon/src/main/webapp/uploadfile/head_img/1724836491.png")));
		imgPart.setContentID("pic");
		
		MimeBodyPart htmlPart = new MimeBodyPart();
		htmlPart.setContent("<h1><a href='www.baidu.com'>百度一下</a><img src='cid:pic'/></h1>", "text/html;charset=utf-8");
		
		contentPart.addBodyPart(imgPart);
		contentPart.addBodyPart(htmlPart);
		content.setContent(contentPart);
		
		emailPart.addBodyPart(attr1);
		emailPart.addBodyPart(attr2);
		emailPart.addBodyPart(content);
		msg.setContent(emailPart);
		
		msg.setFrom(new InternetAddress("[email protected]"));
		msg.setRecipients(RecipientType.TO, InternetAddress.parse("[email protected],[email protected]"));
		msg.setRecipients(RecipientType.CC, InternetAddress.parse("[email protected],[email protected]"));
		Transport.send(msg);
	} catch (Exception e) {
		e.printStackTrace();
	} 
}
 
开发者ID:Awesky,项目名称:awe-awesomesky,代码行数:55,代码来源:EmailHelper.java


注:本文中的javax.mail.Message.setContent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。