public static void sendMail(String mailMessage) { String to = "*****@*****.**"; String from = "FlotaWeb"; String host = "mail.arabesque.ro"; Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); Session session = Session.getDefaultInstance(properties); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Distributie"); message.setText(mailMessage); Transport.send(message); } catch (MessagingException e) { logger.error(Utils.getStackTrace(e)); } }
private void sendReplyFromPostmaster(Mail mail, String stringContent) { try { MailAddress notifier = getMailetContext().getPostmaster(); MailAddress senderMailAddress = mail.getSender(); MimeMessage message = mail.getMessage(); // Create the reply message MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null)); // Create the list of recipients in the Address[] format InternetAddress[] rcptAddr = new InternetAddress[1]; rcptAddr[0] = senderMailAddress.toInternetAddress(); reply.setRecipients(Message.RecipientType.TO, rcptAddr); // Set the sender... reply.setFrom(notifier.toInternetAddress()); // Create the message body MimeMultipart multipart = new MimeMultipart(); // Add message as the first mime body part MimeBodyPart part = new MimeBodyPart(); part.setContent(stringContent, "text/plain"); part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain"); multipart.addBodyPart(part); reply.setContent(multipart); reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType()); // Create the list of recipients in our MailAddress format Set<MailAddress> recipients = new HashSet<MailAddress>(); recipients.add(senderMailAddress); // Set additional headers if (reply.getHeader(RFC2822Headers.DATE) == null) { reply.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new java.util.Date())); } String subject = message.getSubject(); if (subject == null) { subject = ""; } if (subject.indexOf("Re:") == 0) { reply.setSubject(subject); } else { reply.setSubject("Re:" + subject); } reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID()); // Send it off... getMailetContext().sendMail(notifier, recipients, reply); } catch (Exception e) { log("Exception found sending reply", e); } }
/** 根据传入的 Seesion 对象创建混合型的 MIME消息 */ public MimeMessage createMessage(Session session) throws Exception { String from = "*****@*****.**"; String to = "*****@*****.**"; String subject = "创建内含附件、图文并茂的邮件!"; String body = "<h4>内含附件、图文并茂的邮件测试!!!</h4> </br>" + "<a href = http://haolloyin.blog.51cto.com/> 蚂蚁</a></br>" + "<img src = \"cid:logo_jpg\"></a>"; MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject(subject); // 创建邮件的各个 MimeBodyPart 部分 MimeBodyPart attachment01 = createAttachment("F:\\java\\Snake.java"); MimeBodyPart attachment02 = createAttachment("F:\\java\\meng.mp3"); MimeBodyPart content = createContent(body, "F:\\java\\logo.jpg"); // 将邮件中各个部分组合到一个"mixed"型的 MimeMultipart 对象 MimeMultipart allPart = new MimeMultipart("mixed"); allPart.addBodyPart(attachment01); allPart.addBodyPart(attachment02); allPart.addBodyPart(content); // 将上面混合型的 MimeMultipart 对象作为邮件内容并保存 msg.setContent(allPart); msg.saveChanges(); return msg; }
public static MimeMessage createTextMessageWithAttachments( Session session, String subject, String text, Address from, Address[] to, Attachment... attachments) { MimeMessage msg = createEmptyMimeMessage(session); try { msg.setSubject(subject, charset); msg.setFrom(from); msg.setRecipients(Message.RecipientType.TO, to); Multipart multipart = new MimeMultipart(); MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setText(text, charset); multipart.addBodyPart(textBodyPart); if (attachments != null) { for (Attachment attachment : attachments) { appendAttachment(multipart, attachment); } } msg.setContent(multipart); } catch (MessagingException ex) { throw new RuntimeException(ex); } return msg; }
/** Sends the message. Uses superclass username, pass, host, etc. */ public void sendMessage() { if (text == null) { text = asker.askOpenEnded("Please enter a message to send: "); } if (destination == null) { while (destination == null) { try { destination = new InternetAddress(asker.askOpenEnded("Please enter a message recipient: ")); } catch (AddressException e) { System.out.println("Sorry, you entered an invalid email address."); } } } if (subject == null) { subject = asker.askOpenEnded("Please enter a subjectJ: "); } try { MimeMessage msg = new MimeMessage(super.session); msg.setSubject(this.subject); msg.setText(this.text); msg.setFrom(new InternetAddress(super.username)); msg.addRecipient(Message.RecipientType.TO, this.destination); Transport t = super.session.getTransport("smtps"); t.connect(super.host, super.username, super.password); t.sendMessage(msg, msg.getAllRecipients()); } catch (MessagingException mex) { throw new MailException(mex.getMessage()); } super.addMessagesToDB(); System.out.println("Successfully sent message."); }
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 static boolean sendEmail(String from, String to, String subject, String message) { // create a new authenticator for the SMTP server EmailUtilsAuthenticator authenticator = new EmailUtilsAuthenticator(); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty(MAIL_SMTP_HOST, Configuration.getSmtpHost()); // setup the authentication properties.setProperty(MAIL_SMTP_AUTH, "true"); // Get the Session object with the authenticator. Session session = Session.getInstance(properties, authenticator); try { MimeMessage mime = new MimeMessage(session); mime.setFrom(new InternetAddress(from)); mime.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); mime.setSubject(subject); mime.setText(message); // Send it Transport.send(mime); return true; } catch (MessagingException mex) { logger.error("sendEmail(String, String, String, String) - exception ", mex); return false; } }
/** Prepares the message to be sent by the email sender */ protected MimeMessage prepareEmailSenderMessage( Session session, String to, String replyTo, String subject, String body) throws Exception { MimeMessage message = new MimeMessage(session); // From InternetAddress fromAddress = new InternetAddress(emailAddress); fromAddress.setPersonal(emailPersonalName); message.setFrom(fromAddress); // Reply to InternetAddress[] replyToAddress = new InternetAddress[1]; replyToAddress[0] = new InternetAddress(replyTo); replyToAddress[0].setPersonal(emailPersonalName); message.setReplyTo(replyToAddress); // To InternetAddress toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); // Subject/Body message.setSubject(subject); message.setText(body); return message; }
public static void sendEmail(String toEmail, String subject, String body) { try { Properties props = System.getProperties(); props.put("mail.smtp.host", "mail.excellenceserver.com"); // SMTP Host // props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host props.put("mail.smtp.port", "27"); // TLS Port props.put("mail.smtp.auth", "true"); // enable authentication props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS Authenticator auth = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("*****@*****.**", "user@#123"); } }; Session session = Session.getInstance(props, auth); 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"); msg.setFrom(new InternetAddress("*****@*****.**", "user@#123")); msg.setReplyTo(InternetAddress.parse("*****@*****.**", false)); msg.setSubject(subject, "UTF-8"); msg.setText(body, "UTF-8"); msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false)); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); } }
/** * Este método é responsável por enviar email. * * @param pServidorSMTP * @param pDe * @param pPara * @param pCopia * @param pBcc * @param pAssunto * @param pTexto * @return true se o email for enviado, false caso contrário. */ public static boolean enviarEmail( final String pServidorSMTP, final String pDe, final String pPara, final String pCopia, final String pBcc, final String pAssunto, final String pTexto) { Properties mailPprops = new Properties(); mailPprops.put("mail.smtp.host", pServidorSMTP); Session mailSession = Session.getDefaultInstance(mailPprops, null); try { // Mudança: Aplicação usa ";", componente usa "," String para = pPara.replaceAll(";", ","); // Criando a mensagem MimeMessage msg = new MimeMessage(mailSession); // Atribuir rementente msg.setFrom(new InternetAddress(pDe)); // Atribuir destinatários InternetAddress[] endereco = null; // Para if ((para != null) && (!para.equals(""))) { endereco = InternetAddress.parse(para); msg.setRecipients(Message.RecipientType.TO, endereco); } // Cc if ((pCopia != null) && (!pCopia.equals(""))) { endereco = InternetAddress.parse(pCopia); msg.setRecipients(Message.RecipientType.CC, endereco); } // Bcc if ((pBcc != null) && (!pBcc.equals(""))) { endereco = InternetAddress.parse(pBcc); msg.setRecipients(Message.RecipientType.BCC, endereco); } // Atribuir assunto msg.setSubject(pAssunto); // Atribuir corpo do email (texto) if (pTexto != null) msg.setContent(pTexto, "text/html"); msg.setSentDate(new Date()); Transport.send(msg); msg = null; mailSession = null; } catch (MessagingException mex) { if (Constants.DEBUG) { mex.printStackTrace(System.out); } return false; } return true; }
public void send() { // Your SMTP server address here. String smtpHost = "myserver.jeffcorp.com"; // The sender's email address String from = "*****@*****.**"; // The recepients email address String to = "*****@*****.**"; Properties props = new Properties(); // The protocol to use is SMTP props.put("mail.smtp.host", smtpHost); Session session = Session.getDefaultInstance(props, null); try { InternetAddress[] address = {new InternetAddress(to)}; MimeMessage message; message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, to); message.setSubject("Hello from Jeff"); message.setSentDate(sendDate); message.setText("Hello Jeff, \nHow are things going?"); Transport.send(message); System.out.println("email has been sent."); } catch (Exception e) { System.out.println(e); } }
@Override public void run() { LOGGER.info("***********Inside send e-Mail Thread************"); LOGGER.info("Sending email to:: E-mail Address::" + emailModel.getToaddess()); Session mailSession = createSmtpSession(); mailSession.setDebug(true); List<String> toAddresses = new ArrayList<String>(); try { Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject(emailModel.getSubject()); message.setFrom(new InternetAddress(emailModel.getFromAddress())); message.setContent(emailModel.getContent(), "text/html"); toAddresses.add(emailModel.getToaddess()); transport.connect(); Iterator<String> itr = toAddresses.iterator(); while (itr.hasNext()) { String toAddress = (String) itr.next(); message.addRecipients(Message.RecipientType.TO, toAddress); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); } LOGGER.info("Successfully sent email to:: E-mail Address::" + emailModel.getToaddess()); } catch (MessagingException e) { LOGGER.error("Cannot Send email", e); } }
/** * Generate a MimeMessage with the specified attributes * * @param destEmailAddr The destination email address * @param fromEmailAddr The sender email address * @param fromName The senders display name * @param emailSubject The subject * @param emailPlainText The message body (plaintext) * @return The MimeMessage object * @throws Exception */ public static MimeMessage generateMail( String destEmailAddr, String destPersonalName, String fromEmailAddr, String fromName, String emailSubject, String emailPlainText) throws Exception { MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null)); InternetAddress[] toAddrs = InternetAddress.parse(destEmailAddr, false); if (destPersonalName != null) { toAddrs[0].setPersonal(destPersonalName); } InternetAddress from = new InternetAddress(fromEmailAddr); from.setPersonal(fromName); message.setRecipients(Message.RecipientType.TO, toAddrs); message.setFrom(from); message.setSubject(emailSubject); message.setSentDate(new java.util.Date()); MimeMultipart msgbody = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setDataHandler(new DataHandler(new MailDataSource(emailPlainText, "text/plain"))); msgbody.addBodyPart(html); message.setContent(msgbody); return message; }
public static void sendMail(String recipient, String subject, String body) throws MessagingException { Session session = Session.getInstance( properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(username)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); logger.debug("send email to " + recipient); Transport.send(message); }
public boolean send() throws Exception { Properties props = _setProperties(); if (!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) { Session session = Session.getInstance(props, this); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(_from)); InternetAddress[] addressTo = new InternetAddress[_to.length]; for (int i = 0; i < _to.length; i++) { addressTo[i] = new InternetAddress(_to[i]); } msg.setRecipients(MimeMessage.RecipientType.TO, addressTo); msg.setSubject(_subject); msg.setSentDate(new Date()); // setup message body BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(_body); _multipart.addBodyPart(messageBodyPart); // Put parts in message msg.setContent(_multipart); // send email Transport.send(msg); return true; } else { return false; } }
public void SendEmail(String email, String contestToken) { String to = email; String from = "Tyumen_ACM_Society"; String host = "smtp.gmail.com"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Properties props = System.getProperties(); props.setProperty("mail.smtp.host", host); props.put("mail.stmp.user", "*****@*****.**"); props.put("mail.smtp.password", "475508th"); props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); props.setProperty("mail.smtp.socketFactory.fallback", "false"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.auth", "true"); props.put("mail.debug", "true"); props.put("mail.store.protocol", "pop3"); props.put("mail.transport.protocol", "smtp"); Session session = Session.getDefaultInstance(props, new SmtpAuthenticator()); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Registration on acm.utmn.ru"); message.setText( "Hello! Thank you for registration on acm.utmn.ru! Use next token to submit tasks: " + contestToken); Transport t = session.getTransport("smtp"); t.send(message); System.out.println("Message was successfully sent."); } catch (MessagingException mex) { mex.printStackTrace(); } }
public static void main(String[] args) throws MessagingException, IOException { Properties props = new Properties(); try (InputStream in = Files.newInputStream(Paths.get("mail", "mail.properties"))) { props.load(in); } List<String> lines = Files.readAllLines(Paths.get(args[0]), Charset.forName("UTF-8")); String from = lines.get(0); String to = lines.get(1); String subject = lines.get(2); StringBuilder builder = new StringBuilder(); for (int i = 3; i < lines.size(); i++) { builder.append(lines.get(i)); builder.append("\n"); } Console console = System.console(); String password = new String(console.readPassword("Password: ")); Session mailSession = Session.getDefaultInstance(props); // mailSession.setDebug(true); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); message.addRecipient(RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(builder.toString()); Transport tr = mailSession.getTransport(); try { tr.connect(null, password); tr.sendMessage(message, message.getAllRecipients()); } finally { tr.close(); } }
/** * main de prueba * * @param args Se ignoran. */ public static void main(String[] args) { try { // Propiedades de la conexión Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.starttls.disable", "true"); props.setProperty("mail.smtp.auth.plain.disable", "true"); props.setProperty("mail.smtp.port", "465"); props.setProperty("mail.smtp.user", "*****@*****.**"); props.setProperty("mail.smtp.auth", "true"); // Preparamos la sesion Session session = Session.getDefaultInstance(props); session.setDebug(true); // Construimos el mensaje MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("*****@*****.**")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("*****@*****.**")); message.setSubject("Hola"); message.setText("Mensajito con Java Mail" + "de los buenos." + "poque si"); // Lo enviamos. Transport t = session.getTransport("smtp"); t.connect("*****@*****.**", "admmphinv2012"); t.sendMessage(message, message.getAllRecipients()); // Cierre. t.close(); } catch (Exception e) { e.printStackTrace(); } }
/** * Sends an email out * * @param fromAddress * @param toAddresses * @param strSubject * @param strMsg */ public void sendMail( String fromAddress, String strReplyTo, String[] toAddresses, String strSubject, String strMsg) { try { Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromAddress); message.setFrom(from); InternetAddress[] addressTo = new InternetAddress[toAddresses.length]; for (int i = 0; i < toAddresses.length; i++) { addressTo[i] = new InternetAddress(toAddresses[i]); } message.addRecipients(RecipientType.BCC, addressTo); message.setSubject(strSubject); message.setText(strMsg); if (strReplyTo != null) { InternetAddress[] iAddress = new InternetAddress[] {new InternetAddress(strReplyTo)}; message.setReplyTo(iAddress); } Transport.send(message); } catch (Exception e) { throw new WickerException(e); } }
private MimeMessage getMessage(Email email, Session session) throws AddressException, MessagingException { MimeMessage result = new MimeMessage(session); result.setFrom(new InternetAddress(email.getFrom())); result.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.getTo())); result.setSubject(email.getSubject()); if (email.getAttachment() != null) { // message body part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(email.getMsg()); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); MimeBodyPart attachmentPart = new MimeBodyPart(); DataSource attachmentSource = new ByteArrayDataSource( email.getAttachment().getContent(), email.getAttachment().getAttachmentType()); attachmentPart.setDataHandler(new DataHandler(attachmentSource)); attachmentPart.setFileName(email.getAttachment().getFileName()); multipart.addBodyPart(attachmentPart); result.setContent(multipart); } else { result.setContent(email.getMsg(), "text/plain"); } return result; }
public boolean send() { try { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", "smtp.gmail.com"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.debug", "true"); props.put("mail.smtp.socketFactory.port", "465"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props, new GJMailAuthenticator()); session.setDebug(true); Transport transport = session.getTransport(); InternetAddress addressFrom = new InternetAddress("*****@*****.**"); MimeMessage message = new MimeMessage(session); message.setSender(addressFrom); message.setSubject(subject); message.setContent(text, "text/html"); InternetAddress addressTo = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO, addressTo); transport.connect(); Transport.send(message); transport.close(); System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); return false; } return true; }
public void enviarEmail() { FacesContext context = FacesContext.getCurrentInstance(); AutenticaUsuario autenticaUsuario = new AutenticaUsuario(GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL); Session session = Session.getDefaultInstance(this.configuracaoEmail(), autenticaUsuario); session.setDebug(true); try { Transport envio = null; MimeMessage email = new MimeMessage(session); email.setRecipient(Message.RecipientType.TO, new InternetAddress(this.para)); email.setFrom(new InternetAddress(this.de)); email.setSubject(this.assunto); email.setContent(this.mensagem, "text/plain"); email.setSentDate(new Date()); envio = session.getTransport("smtp"); envio.connect(GmailBean.SERVIDOR_SMTP, GmailBean.CONTA_GMAIL, GmailBean.SENHA_GMAIL); email.saveChanges(); envio.sendMessage(email, email.getAllRecipients()); envio.close(); context.addMessage(null, new FacesMessage("E-mail enviado com sucesso")); } catch (AddressException e) { FacesMessage msg = new FacesMessage("Erro ao montar mensagem de e-mail! Erro: " + e.getMessage()); context.addMessage(null, msg); return; } catch (MessagingException e) { FacesMessage msg = new FacesMessage("Erro ao enviar e-mail! Erro: " + e.getMessage()); context.addMessage(null, msg); return; } }
public void test() throws Exception { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", SMTP_HOST_NAME); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(true); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(username.getText())); message.setSubject(subject.getText()); String s = msgfield.getText(); message.setContent(s, "text/plain"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailID.getText())); System.out.println("8i m here "); try { transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, username.getText(), password.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "invalid username or password"); } System.out.println("8i m here also yaar"); // transport.sendMessage(message,message.getRecipients(Message.RecipientType.TO)); transport.sendMessage(message123, message123.getAllRecipients()); transport.close(); System.out.println(s); }
public static void main(String args[]) throws Exception { // // create the generator for creating an smime/compressed message // SMIMECompressedGenerator gen = new SMIMECompressedGenerator(); // // create the base for our message // MimeBodyPart msg = new MimeBodyPart(); msg.setText("Hello world!"); MimeBodyPart mp = gen.generate(msg, new ZlibCompressor()); // // Get a Session object and create the mail message // Properties props = System.getProperties(); Session session = Session.getDefaultInstance(props, null); Address fromUser = new InternetAddress("\"Eric H. Echidna\"<*****@*****.**>"); Address toUser = new InternetAddress("*****@*****.**"); MimeMessage body = new MimeMessage(session); body.setFrom(fromUser); body.setRecipient(Message.RecipientType.TO, toUser); body.setSubject("example compressed message"); body.setContent(mp.getContent(), mp.getContentType()); body.saveChanges(); body.writeTo(new FileOutputStream("compressed.message")); }
public void setMessageContent( MimeMessage message, String subject, String bodyText, String bodyHtml) { try { message.setSubject(subject); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(bodyText.toString(), "UTF-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(bodyHtml.toString(), "text/html; charset=UTF-8"); MimeMultipart multiPart = new MimeMultipart(); // "alternative" means display only one or the other, "mixed" means both multiPart.setSubType("alternative"); // I read something on the internet saying to put the text part first // so sucktastic mail clients see it first multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); } catch (MessagingException e) { throw new RuntimeException("failed to put together MIME message", e); } }
public void mail(String toAddress, String subject, String body) { Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.ssl.enable", true); Authenticator authenticator = null; if (login) { props.put("mail.smtp.auth", true); authenticator = new Authenticator() { private PasswordAuthentication pa = new PasswordAuthentication(username, password); @Override public PasswordAuthentication getPasswordAuthentication() { return pa; } }; } Session s = Session.getInstance(props, authenticator); s.setDebug(debug); MimeMessage email = new MimeMessage(s); try { email.setFrom(new InternetAddress(from)); email.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); email.setSubject(subject); email.setSentDate(new Date()); email.setText(body); Transport.send(email); } catch (MessagingException ex) { ex.printStackTrace(); } }
private static void sendSimpleEmails(String toUserName, int count) throws MessagingException, InterruptedException, IOException { Session session = Session.getInstance(getEmailProperties()); Random random = new Random(); int emailSize = emails.length; for (int i = 1; i <= count; i++) { Thread.sleep(10000); 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.setSentDate(new Date()); SimpleMessage randomMessage = SimpleMessage.values()[random.nextInt(SimpleMessage.values().length)]; msg.setSubject(randomMessage.name()); msg.setText(randomMessage.getBody()); Transport.send(msg); } }
public static void sendEmail( InternetAddress from, InternetAddress to, String content, String requester) throws MessagingException, UnsupportedEncodingException { Properties props = new Properties(); props.put("mail.transport.protocol", "smtps"); props.put("mail.smtps.host", SMTP_HOST_NAME); props.put("mail.smtps.auth", "true"); Session mailSession = Session.getDefaultInstance(props); mailSession.setDebug(false); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject("MN Traffic Generation is used by " + requester); message.setContent(content, "text/plain"); message.addRecipient(Message.RecipientType.TO, to); InternetAddress[] replyto = new InternetAddress[1]; replyto[0] = from; message.setFrom(from); message.setReplyTo(replyto); message.setSender(from); transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); }
@Test public void shouldReceiveMessageAndSendOutgoingMail() throws Exception { // send test message to camel@localhost MimeMessage msg = new MimeMessage(session); msg.setSubject(SUBJECT); msg.setRecipients(RecipientType.TO, "camel@localhost"); msg.setText(PAYLOAD); Transport.send(msg); Thread.sleep(500); Message[] messages = inbox.getMessages(); // verify mailbox states, note that mock javamail do not create new // folders, so everything goes to same place assertEquals(2, messages.length); messages = read.getMessages(); assertEquals(2, messages.length); assertEquals(PAYLOAD, messages[0].getContent()); assertEquals(SUBJECT, messages[0].getSubject()); messages = riderInbox.getMessages(); assertEquals(1, messages.length); assertEquals("Forwarded message", messages[0].getSubject()); assertEquals(PAYLOAD, messages[0].getContent()); }
public void sendMail(String from, String to, String subject, String Body) { Properties props = new Properties(); // String host="smtp.gmail.com"; props.put("mail.transport.protocol", protocol); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", auth); props.put("mail.smtp.starttls.enable", starttls); props.put("mail.smtp.socketFactory.port", socketFactoryPort); props.put("mail.smtp.socketFactory.class", socketFactoryClass); props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback); Session session = Session.getDefaultInstance( props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( usrname, pasword); // Specify the Username and the PassWord } }); MimeMessage message = new MimeMessage(session); try { InternetAddress addressFrom = new InternetAddress(from); message.setFrom(addressFrom); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(Body); Transport.send(message); } catch (MessagingException ex) { System.err.println("Cannot send email. " + ex); } }