use of javax.mail.Message in project SpringStepByStep by JavaProgrammerLB.
the class SendHTMLEmail method main.
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "destinationemail@gmail.com";
// Sender's email ID needs to be mentioned
String from = "fromemail@gmail.com";
//change accordingly
final String username = "manishaspatil";
//change accordingly
final String password = "******";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Send the actual HTML message, as big as you like
message.setContent("<h1>This is actual message embedded in HTML tags</h1>", "text/html;charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
use of javax.mail.Message in project SpringStepByStep by JavaProgrammerLB.
the class SendHTMLEmailWithTemplate method main.
public static void main(String[] args) throws Exception {
Properties props = new Properties();
try {
props.load(new FileInputStream(new File("settings.properties")));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
Session session = Session.getDefaultInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "******");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@gmail.com"));
message.setSubject("Testing Subject");
BodyPart body = new MimeBodyPart();
// freemarker stuff.
Configuration cfg = new Configuration();
Template template = cfg.getTemplate("html-mail-template.ftl");
Map<String, String> rootMap = new HashMap<String, String>();
rootMap.put("to", "liubei");
rootMap.put("body", "Sample html email using freemarker");
rootMap.put("from", "liubei");
Writer out = new StringWriter();
template.process(rootMap, out);
// freemarker stuff ends.
/* you can add html tags in your text to decorate it. */
body.setContent(out.toString(), "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
body = new MimeBodyPart();
String filename = "hello.txt";
DataSource source = new FileDataSource(filename);
body.setDataHandler(new DataHandler(source));
body.setFileName(filename);
multipart.addBodyPart(body);
message.setContent(multipart, "text/html;charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
e.printStackTrace();
}
System.out.println("Done....");
}
use of javax.mail.Message in project SpringStepByStep by JavaProgrammerLB.
the class SendAttachmentInEmail method main.
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "destinationemail@gmail.com";
// Sender's email ID needs to be mentioned
String from = "fromemail@gmail.com";
//change accordingly
final String username = "manishaspatil";
//change accordingly
final String password = "******";
// Assuming you are sending email through relay.jangosmtp.net
String host = "relay.jangosmtp.net";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
use of javax.mail.Message in project SpringStepByStep by JavaProgrammerLB.
the class AccountEmailServiceTest method testSendMail.
@Test
public void testSendMail() throws Exception {
ApplicationContext ctx = new ClassPathXmlApplicationContext("account-email.xml");
AccountEmailService accountEmailService = (AccountEmailService) ctx.getBean("accountEmailService");
String subject = "Test Subject";
String htmlText = "<h3>Test</h3>";
accountEmailService.sendMail("test2@juvenxu.com", subject, htmlText);
greenMail.waitForIncomingEmail(2000, 1);
Message[] msgs = greenMail.getReceivedMessages();
assertEquals(1, msgs.length);
assertEquals(subject, msgs[0].getSubject());
assertEquals(htmlText, GreenMailUtil.getBody(msgs[0]).trim());
}
use of javax.mail.Message in project jmeter by apache.
the class MailReaderSampler method sample.
/**
* {@inheritDoc}
*/
@Override
public SampleResult sample(Entry e) {
SampleResult parent = new SampleResult();
// Did sample succeed?
boolean isOK = false;
final boolean deleteMessages = getDeleteMessages();
final String serverProtocol = getServerType();
parent.setSampleLabel(getName());
String samplerString = toString();
parent.setSamplerData(samplerString);
/*
* Perform the sampling
*/
// Start timing
parent.sampleStart();
try {
// Create empty properties
Properties props = new Properties();
if (isUseStartTLS()) {
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE);
if (isEnforceStartTLS()) {
// Requires JavaMail 1.4.2+
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE);
}
}
if (isTrustAllCerts()) {
if (isUseSSL()) {
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
} else if (isUseStartTLS()) {
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"), TRUST_ALL_SOCKET_FACTORY);
// $NON-NLS-1$
props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
}
} else if (isUseLocalTrustStore()) {
File truststore = new File(getTrustStoreToUse());
log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath());
truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
log.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath());
if (!truststore.exists()) {
log.info("load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution.");
throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath());
}
}
if (isUseSSL()) {
// Requires JavaMail 1.4.2+
// $NON-NLS-1$
props.put(// $NON-NLS-1$
mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
// $NON-NLS-1$
props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
} else if (isUseStartTLS()) {
// Requires JavaMail 1.4.2+
// $NON-NLS-1$
props.put(// $NON-NLS-1$
mailProp(serverProtocol, "ssl.socketFactory"), new LocalTrustStoreSSLSocketFactory(truststore));
// $NON-NLS-1$
props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE);
}
}
// Get session
Session session = Session.getInstance(props, null);
// Get the store
Store store = session.getStore(serverProtocol);
store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());
// Get folder
Folder folder = store.getFolder(getFolder());
if (deleteMessages) {
folder.open(Folder.READ_WRITE);
} else {
folder.open(Folder.READ_ONLY);
}
final int messageTotal = folder.getMessageCount();
int n = getNumMessages();
if (n == ALL_MESSAGES || n > messageTotal) {
n = messageTotal;
}
// Get directory
Message[] messages = folder.getMessages(1, n);
StringBuilder pdata = new StringBuilder();
pdata.append(messages.length);
pdata.append(" messages found\n");
parent.setResponseData(pdata.toString(), null);
parent.setDataType(SampleResult.TEXT);
// $NON-NLS-1$
parent.setContentType("text/plain");
final boolean headerOnly = getHeaderOnly();
busy = true;
for (Message message : messages) {
StringBuilder cdata = new StringBuilder();
SampleResult child = new SampleResult();
child.sampleStart();
// $NON-NLS-1$
cdata.append("Message ");
cdata.append(message.getMessageNumber());
child.setSampleLabel(cdata.toString());
child.setSamplerData(cdata.toString());
cdata.setLength(0);
final String contentType = message.getContentType();
// Store the content-type
child.setContentType(contentType);
// RFC 822 uses ascii per default
child.setDataEncoding(RFC_822_DEFAULT_ENCODING);
// Parse the content-type
child.setEncodingAndType(contentType);
if (isStoreMimeMessage()) {
// Don't save headers - they are already in the raw message
ByteArrayOutputStream bout = new ByteArrayOutputStream();
message.writeTo(bout);
// Save raw message
child.setResponseData(bout.toByteArray());
child.setDataType(SampleResult.TEXT);
} else {
// Javadoc for the API says this is OK
@SuppressWarnings("unchecked") Enumeration<Header> hdrs = message.getAllHeaders();
while (hdrs.hasMoreElements()) {
Header hdr = hdrs.nextElement();
String value = hdr.getValue();
try {
value = MimeUtility.decodeText(value);
} catch (UnsupportedEncodingException uce) {
// ignored
}
cdata.append(hdr.getName()).append(": ").append(value).append("\n");
}
child.setResponseHeaders(cdata.toString());
cdata.setLength(0);
if (!headerOnly) {
appendMessageData(child, message);
}
}
if (deleteMessages) {
message.setFlag(Flags.Flag.DELETED, true);
}
child.setResponseOK();
if (child.getEndTime() == 0) {
// Avoid double-call if addSubResult was called.
child.sampleEnd();
}
parent.addSubResult(child);
}
// Close connection
folder.close(true);
store.close();
parent.setResponseCodeOK();
parent.setResponseMessageOK();
isOK = true;
} catch (NoClassDefFoundError | IOException ex) {
// No need to log normally, as we set the status
log.debug("", ex);
// $NON-NLS-1$
parent.setResponseCode("500");
parent.setResponseMessage(ex.toString());
} catch (MessagingException ex) {
// No need to log normally, as we set the status
log.debug("", ex);
// $NON-NLS-1$
parent.setResponseCode("500");
// $NON-NLS-1$
parent.setResponseMessage(ex.toString() + "\n" + samplerString);
} finally {
busy = false;
}
if (parent.getEndTime() == 0) {
// not been set by any child samples
parent.sampleEnd();
}
parent.setSuccessful(isOK);
return parent;
}
Aggregations