當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。