/** * 处理附件型邮件时,需要为邮件体和附件体分别创建BodyPort对象 然后将其置入MimeMultipart对象中作为一个整体进行发送 */ @Override protected void setContent(MimeMessage message) throws MailException { try { Multipart multipart = new MimeMultipart(); // 文本 BodyPart textBodyPart = new MimeBodyPart(); multipart.addBodyPart(textBodyPart); textBodyPart.setContent(text, "text/html;charset=" + charset); // 附件 for (File attachment : attachments) { BodyPart fileBodyPart = new MimeBodyPart(); multipart.addBodyPart(fileBodyPart); FileDataSource fds = new FileDataSource(attachment); fileBodyPart.setDataHandler(new DataHandler(fds)); // 中文乱码 String attachmentName = fds.getName(); fileBodyPart.setFileName(MimeUtility.encodeText(attachmentName)); } // 内容 message.setContent(multipart); } catch (Exception e) { new MailException(e.getMessage()); } }
@Override public void run(CodeCenterServerProxy proxy) throws Exception { // Create the attachment create bean String path = ds.getFile().getPath(); ApplicationNameVersionToken appToken = new ApplicationNameVersionToken(); appToken.setName(applicationName); appToken.setVersion(applicationVersion); ApplicationAttachmentCreate attachmentCreateBean = new ApplicationAttachmentCreate(); attachmentCreateBean.setApplicationId(appToken); attachmentCreateBean.setAttachmentContent(new DataHandler(ds)); attachmentCreateBean.setDescription(descripion); attachmentCreateBean.setFileName(path); attachmentCreateBean.setName(attachmentName != null ? attachmentName : ds.getName()); // Add the attachment String attachmentId = proxy.getApplicationApi().createApplicationAttachment(attachmentCreateBean); // Print success information System.out.println( "Successfully added attachment \"" + path + "\"" + (attachmentName != null ? " as \"" + attachmentName + "\"" : "") + " to application \"" + applicationName + "\" version \"" + applicationVersion + "\" with attachment ID " + attachmentId + "."); }
public synchronized void sendImage( String subject, String body, String sender, String recipients, File attachment) throws Exception { try { MimeMessage message = new MimeMessage(session); message.setSender(new InternetAddress(sender)); message.setSubject(subject); MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(body); MimeBodyPart mbp2 = new MimeBodyPart(); FileDataSource fds = new FileDataSource(attachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); message.setContent(mp); if (recipients.indexOf(',') > 0) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients)); else message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); Transport.send(message); } catch (Exception e) { Log.e("GmalSender", "Exception", e); } }
/** 根据传入的文件路径创建附件并返回 */ public MimeBodyPart createAttachment(String fileName) throws Exception { MimeBodyPart attachmentPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(fileName); attachmentPart.setDataHandler(new DataHandler(fds)); attachmentPart.setFileName(fds.getName()); return attachmentPart; }
public void testAttachments() throws Exception { Properties props = System.getProperties(); props.setProperty("mail.smtp.host", "localhost"); props.setProperty("mail.smtp.port", SMTP_PORT + ""); Session session = Session.getInstance(props); MimeMessage baseMsg = new MimeMessage(session); MimeBodyPart bp1 = new MimeBodyPart(); bp1.setHeader("Content-Type", "text/plain"); bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\""); // Attach the file MimeBodyPart bp2 = new MimeBodyPart(); FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH); DataHandler dh = new DataHandler(fileAttachment); bp2.setDataHandler(dh); bp2.setFileName(fileAttachment.getName()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bp1); multipart.addBodyPart(bp2); baseMsg.setFrom(new InternetAddress("Ted <*****@*****.**>")); baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**")); baseMsg.setSubject("Test Big attached file message"); baseMsg.setContent(multipart); baseMsg.saveChanges(); LOG.debug("Send started"); Transport t = new SMTPTransport(session, new URLName("smtp://*****:*****@example.org")}); t.close(); started = System.currentTimeMillis() - started; LOG.info("Elapsed ms = " + started); WiserMessage msg = server.getMessages().get(0); assertEquals(1, server.getMessages().size()); assertEquals("*****@*****.**", msg.getEnvelopeReceiver()); File compareFile = File.createTempFile("attached", ".tmp"); LOG.debug("Writing received attachment ..."); FileOutputStream fos = new FileOutputStream(compareFile); ((MimeMultipart) msg.getMimeMessage().getContent()) .getBodyPart(1) .getDataHandler() .writeTo(fos); fos.close(); LOG.debug("Checking integrity ..."); assertTrue(checkIntegrity(new File(BIGFILE_PATH), compareFile)); LOG.debug("Checking integrity DONE"); compareFile.delete(); msg.dispose(); }
public FileAttachment(ContentDisposition contentDisposition, File file) { super(); FileDataSource fileDataSource = new FileDataSource(file); try { super.setFileName(fileDataSource.getName()); super.setMimeType(fileDataSource.getContentType()); super.setContentDisposition(contentDisposition); super.setBytes(toByteArray(file)); } catch (IOException e) { throw new MailException("Can't create File Attachment", e); } }
/** * 添加附件 * * @param filename String */ public boolean addFileAffix(String filename) { try { BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); bp.setFileName(fileds.getName()); mp.addBodyPart(bp); return true; } catch (Exception e) { System.err.println("增加邮件附件" + filename + "发生错误" + e); return false; } }
/** set the file */ public void setFile(String filename) { fds = new FileDataSource(filename); System.out.println("DCHTest2: FileDataSource created"); if (!fds.getContentType().equals("text/plain")) { System.out.println("Type must be text/plain"); System.exit(1); } }
private boolean sendEmail(UserModel user, X509Metadata metadata, File zip) { // send email try { if (mail.isReady()) { Message message = mail.createMessage(user.emailAddress); message.setSubject("Your Gitblit client certificate for " + metadata.serverHostname); // body of email String body = X509Utils.processTemplate( new File(folder, X509Utils.CERTS + File.separator + "mail.tmpl"), metadata); if (StringUtils.isEmpty(body)) { body = MessageFormat.format( "Hi {0}\n\nHere is your client certificate bundle.\nInside the zip file are installation instructions.", user.getDisplayName()); } Multipart mp = new MimeMultipart(); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(body); mp.addBodyPart(messagePart); // attach zip MimeBodyPart filePart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(zip); filePart.setDataHandler(new DataHandler(fds)); filePart.setFileName(fds.getName()); mp.addBodyPart(filePart); message.setContent(mp); mail.sendNow(message); return true; } else { JOptionPane.showMessageDialog( GitblitAuthority.this, "Sorry, the mail server settings are not configured properly.\nCan not send email.", Translation.get("gb.error"), JOptionPane.ERROR_MESSAGE); } } catch (Exception e) { Utils.showException(GitblitAuthority.this, e); } return false; }
private static void sendBigEmail(String toUserName) throws MessagingException, IOException { Session session = Session.getInstance(getEmailProperties()); Random random = new Random(); int emailSize = emails.length; MimeMessage msg = new MimeMessage(session); InternetAddress from = new InternetAddress(emails[random.nextInt(emailSize)]); InternetAddress to = new InternetAddress(toUserName); msg.setFrom(from); msg.addRecipient(Message.RecipientType.TO, to); msg.setSubject("New book " + UUID.randomUUID().toString()); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText("Hi, all \n I sent you book.\n Thank you, "); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(new ClassPathResource(BIG_FILE).getFile()); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // set the Date: header msg.setSentDate(new Date()); // msg.setText(String.format(TEXT, name)); // send message Transport.send(msg); }
/** * 添加附件 * * @param filename String */ public boolean addFileAffix(String filename) { System.out.println("增加邮件附件:" + filename); try { BodyPart bp = new MimeBodyPart(); FileDataSource fileds = new FileDataSource(filename); bp.setDataHandler(new DataHandler(fileds)); String attachName = fileds.getName(); // System.out.println(attachName); // System.out.println(new String(attachName.getBytes("utf-8"),"gbk")); // System.out.println(new String(MimeUtility.encodeWord(""))); attachName = new String(MimeUtility.encodeWord(attachName)); bp.setFileName(attachName); mp.addBodyPart(bp); return true; } catch (Exception e) { System.err.println("增加邮件附件:" + filename + "发生错误!" + e); return false; } }
/** * Sort the quotes. * * @param portlet The jsp-based portlet that is being built. * @param rundata The turbine rundata context for this request. */ public void doEmail(RunData rundata, Portlet portlet) { StringBuffer emailBody = new StringBuffer(); PortletEntry entry = (PortletEntry) Registry.getEntry(Registry.PORTLET, portlet.getName()); Iterator i = entry.getParameterNames(); while (i.hasNext()) { String name = (String) i.next(); Parameter param = entry.getParameter(name); if (param.isHidden() == false) { String title = param.getTitle(); String value = portlet.getPortletConfig().getInitParameter(name); value = value == null || value.length() == 0 ? "NOT PROVIDED" : value; emailBody.append(title); emailBody.append(" ===> "); emailBody.append(value); emailBody.append("\n\n"); } } String emailSmtp = JetspeedResources.getString(JetspeedResources.MAIL_SERVER_KEY); String emailFrom = JetspeedResources.getString("mail.support", "*****@*****.**"); String emailTo = rundata.getParameters().getString("emailTo", "*****@*****.**"); String emailAttachment = rundata.getRequest().getParameter("emailAttachment"); try { String emailText = emailBody.toString(); // Create the JavaMail session java.util.Properties properties = System.getProperties(); properties.put("mail.smtp.host", emailSmtp); Session emailSession = Session.getInstance(properties, null); // Construct the message MimeMessage message = new MimeMessage(emailSession); // Set the from address Address fromAddress = new InternetAddress(emailFrom); message.setFrom(fromAddress); // Parse and set the recipient addresses Address[] toAddresses = InternetAddress.parse(emailTo); message.setRecipients(Message.RecipientType.TO, toAddresses); // Set the subject and text message.setSubject("Jetspeed Questionnaire from " + rundata.getUser().getEmail()); message.setText(emailText); // Attach file with message if (emailAttachment != null) { File file = new File(emailAttachment); if (file.exists()) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(emailText); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(emailAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message message.setContent(mp); } else { message.setText(emailBody.toString()); } } // send the message Transport.send(message); // Display confirmation rundata.getRequest().setAttribute("email", emailBody.toString()); String confirmTemplate = portlet .getPortletConfig() .getInitParameter("confirm.template", "JetspeedQuestionnaireConfirmation.jsp"); // this.setTemplate(rundata, portlet, confirmTemplate); setTemplate(rundata, confirmTemplate, true); rundata.setMessage("Email successfully sent"); } catch (Exception e) { logger.error("Exception", e); rundata.setMessage("Error sending email: " + e); } // buildNormalContext(portlet, rundata); }
private void doit(String[] argv) { String to = null, subject = null, from = null, replyTo = null, cc = null, bcc = null, url = null; String mailhost = null; String mailer = "MsgSend"; String protocol = null, host = null, user = null, password = null, record = null; String filename = null, msg_text = null, inline_filename = null; boolean debug = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-X")) { msg_text = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { filename = argv[++optind]; } else if (argv[optind].equals("-i")) { inline_filename = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator (from) from = argv[++optind]; } else if (argv[optind].equals("-r")) { // reply-to replyTo = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.err.println(USAGE_TEXT); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); // XXX - could use Session.getTransport() and Transport.connect() // XXX - assume we're using SMTP if (mailhost != null) props.put("mail.smtp.host", mailhost); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); if (reply_to_list == null && replyTo != null) { reply_to_list = new InternetAddress[1]; reply_to_list[0] = new InternetAddress(replyTo); msg.setReplyTo(reply_to_list); } else msg.setReplyTo(reply_to_list); if (dis_list == null) { dis_list = new InternetAddress[1]; dis_list[0] = new InternetAddress(to); } msg.setRecipients(Message.RecipientType.TO, dis_list); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); // in-line file contents if specified if (inline_filename != null) { msg_text = readFile(inline_filename); } // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(msg_text); // create the Multipart and add the text part Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); // create additional message part(s) // attach the file or files to the message if (filename != null) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filename); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); mbp1.setText(msg_text + "\n\nAttachment: " + filename); System.out.println("Added attachment: " + filename); } if (attachments != null) { Iterator i = attachments.iterator(); StringBuffer list = null; while (i.hasNext()) { String name = (String) i.next(); MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(name); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); if (list == null) { list = new StringBuffer(name); } else { list.append(", " + name); } System.out.println("Added attachment: " + name); mbp1.setText(msg_text + "\nAttachment(s): " + list); } } // add the Multipart to the message msg.setContent(mp); msg.setSubject(subject); // jgfrun collect(in, msg); msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off Transport.send(msg); System.out.println("Mail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { System.err.println("Could not MsgSend.doit"); e.printStackTrace(); } } // doit
/** Try remove file when object destroyed. {@inheritDoc} */ @Override protected void finalize() throws Throwable { super.finalize(); File file = getFile(); if (file.exists()) file.delete(); }
public void senderMail(final MailJava mail) throws UnsupportedEncodingException, MessagingException { Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", mail.getSmtpHostMail()); props.setProperty("mail.smtp.auth", mail.getSmtpAuth()); props.setProperty("mail.smtp.starttls.enable", mail.getSmtpStarttls()); props.setProperty("mail.smtp.port", mail.getSmtpPortMail()); props.setProperty("mail.mime.charset", mail.getCharsetMail()); // classe anonima que realiza a autenticação // do usuario no servidor de email. Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mail.getUserMail(), mail.getPassMail()); } }; // Cria a sessao passando as propriedades e a autenticação Session session = Session.getDefaultInstance(props, auth); // Gera um log no console referente ao processo de envio session.setDebug(true); // cria a mensagem setando o remetente e seus destinatários Message msg = new MimeMessage(session); // aqui seta o remetente msg.setFrom(new InternetAddress(mail.getUserMail(), mail.getFromNameMail())); boolean first = true; for (Map.Entry<String, String> map : mail.getToMailsUsers().entrySet()) { if (first) { // setamos o 1° destinatario msg.addRecipient( Message.RecipientType.TO, new InternetAddress(map.getKey(), map.getValue())); first = false; } else { // setamos os demais destinatarios msg.addRecipient( Message.RecipientType.CC, new InternetAddress(map.getKey(), map.getValue())); } } // Adiciona um Assunto a Mensagem msg.setSubject(mail.getSubjectMail()); // Cria o objeto que recebe o texto do corpo do email MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getBodyMail(), mail.getTypeTextMail()); // Monta a mensagem SMTP inserindo o conteudo, texto e anexos Multipart mps = new MimeMultipart(); if (mail.getFileMails() != null) { for (int index = 0; index < mail.getFileMails().size(); index++) { // Cria um novo objeto para cada arquivo, e anexa o arquivo MimeBodyPart attachFilePart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(mail.getFileMails().get(index)); attachFilePart.setDataHandler(new DataHandler(fds)); attachFilePart.setFileName(fds.getName()); // adiciona os anexos da mensagem mps.addBodyPart(attachFilePart, index); } } // adiciona o corpo texto da mensagem mps.addBodyPart(textPart); // adiciona a mensagem o conteúdo texto e anexo msg.setContent(mps); // Envia a Mensagem Transport.send(msg); }
/** * Constructor for initializing the attachment with a file * * @param file The file object */ public EmailAttachment(File file) { datasource = new FileDataSource(file); shortFilename = file.getName(); datasource.setFileTypeMap(new AttachmentTypeMap()); }
/** * メールを送信する * * @param fad 送信元アドレス * @param fan 送信元名 * @param tad 送信先アドレス * @param tan 送信先名 * @param tle タイトル * @param mes 本文 * @param atd 添付ファイルパス * @author kazua */ public String sendMailProc( String fad, String fan, String tad, String tan, String tle, String mes, String atd) { try { // プロパティ作成 Properties ppt = System.getProperties(); // メールパターンマッチ Pattern ptn = Pattern.compile(mailP); Matcher mc = ptn.matcher(fad); if (!mc.matches()) { return "送信元メールアドレスが異常です:" + fad; } mc = ptn.matcher(tad); if (!mc.matches()) { return "送信先メールアドレスが異常です:" + tad; } // パラメータチェック if ((tle == null || tle.equals("")) && (mes == null || mes.equals("")) && (atd == null || atd.equals(""))) { return "タイトル、本文、添付ファイルが全て未指定です"; } // SMTPアドレス設定 ppt.put("mail.smtp.host", "***.***.***.***"); // メールセッション作成 Session ssm = Session.getDefaultInstance(ppt, null); MimeMessage mms = new MimeMessage(ssm); // 送信元設定 mms.setFrom(new InternetAddress(fad, MimeUtility.encodeWord(fan, "UTF-8", "B"))); // 送信先設定 InternetAddress adr = new InternetAddress(tad, MimeUtility.encodeWord(tan, "UTF-8", "B")); mms.setRecipient(Message.RecipientType.TO, adr); // メール形式設定 mms.setHeader("Content-Type", "text/plain"); // 題名設定 if (tle != null && !tle.equals("")) { mms.setSubject(MimeUtility.encodeText(tle, "UTF-8", "B")); } // メール本体作成 MimeMultipart mmp = new MimeMultipart(); // 本文設定 if (mes != null && !mes.equals("")) { MimeBodyPart tpt = new MimeBodyPart(); tpt.setContent(mes, "text/plain; charset=\"UTF-8\""); mmp.addBodyPart(tpt); } // 添付ファイル設定 if (atd != null && !atd.equals("")) { MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(atd); DataHandler dhr = new DataHandler(fds); mbp.setDataHandler(dhr); mbp.setFileName(MimeUtility.encodeText(fds.getName(), "iso-2022-jp", "B")); mmp.addBodyPart(mbp); } mms.setContent(mmp); // メール送信 Transport.send(mms); return "メール送信完了"; } catch (Exception e) { return "メール送信失敗:" + e.toString(); } }