I have an web application in which i am sending mail to user. Following is my code.
String host = "smtp.gmail.com";
String pwd = "123";
String from = "sender#gmail.com";
String to = "receiver#gmail.com";
String subject = "Test";
String messageText = "This is demo mail";
int port = 587;
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");
java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] add = {new InternetAddress(to)};
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setRecipients(Message.RecipientType.TO, add);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText); //Actual msg
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, from, pwd);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
This code is executed on local but fails on server domain. I have search a lot but that solution didn't work for me.
I tried a lot like replacing transport.connect(host, from, pwd); with transport.connect(host, 587, from, pwd); or 465and also String host="smtp.gmail.com"; with static domain IP. but still not working.
can anyone figure out what i am missing..?
Here is working example.
If this didn't work then there must be a problem with your server..
public static void sendEmail(String host, String port, final String userName, final String password, String recipient, String subject, String message, File attachFile) throws AddressException, MessagingException, UnsupportedEncodingException {
// sets SMTP server properties
try {
logger.info("Sending Email to : " + recipient + " Subject :" + subject);
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");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName, userName));
if (recipient.contains(";")) {
String[] recipientList = recipient.split(";");
InternetAddress[] recipientAddress = new InternetAddress[recipientList.length];
int counter = 0;
for (String obj: recipientList) {
recipientAddress[counter] = new InternetAddress(obj.trim());
counter++;
}
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
} else {
InternetAddress[] recipientAddress = {
new InternetAddress(recipient)
};
msg.setRecipients(Message.RecipientType.TO, recipientAddress);
}
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFile != null) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(attachFile);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
} catch (Exception e) {
logger.error("ERROR In Sending Email :" + e, e);
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am working on user registration function.Now I headed a new problem.
I want to send an Email to user after user done with the Registration.
#PostMapping("registration")
public String registration(Model model,
#Valid #ModelAttribute("cool") User user,
BindingResult bindingresult) {
if (bindingresult.hasErrors()) {
model.addAttribute("cool", user);
return "registration";
}
model.addAttribute("user", user);
data.addUser(user);
//------------------------Email----------------//
// Here I need a solution
//------------------------Email----------------//
return "success";
}
For example:
my Email Address is: Vincent#gmail.com
I want to send an Email from my Email(or from localhost) to User's Email.
You can use Gmail SMTP via TLS
private static String USER_NAME = "Gmail Username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "gbxxfgfhujdfqndd"; // GMail password
public static boolean sendEmail(String RECIPIENT, String sub, String title, String body, String under_line_text,
String end_text) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = {
RECIPIENT
}; // list of recipient email addresses
String subject = sub;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++) {
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<div style=\" background-color: white;width: 25vw;height:auto;border: 20px solid grey;padding: 50px;margin:100 auto;\">\n" +
"<h1 style=\"text-align: center;font-size:1.5vw\">" + title + "</h1>\n" + "<div align=\"center\">" +
"<h2 style=\"text-align: center;font-size:1.0vw\">" + body + "</h2>" +
"<h3 style=\"text-align: center;text-decoration: underline;text-decoration-color: red;font-size:0.9vw\">" +
under_line_text + "</h3><br><h4 style=\"text-align: center;font-size:0.7vw\">" + end_text +
" </h4></div>";
messageBodyPart.setContent(htmlText, "text/html");
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (AddressException ae) {
ae.printStackTrace();
} catch (MessagingException me) {
me.printStackTrace();
}
return true;
}
Or Gmail via SSL in which you should add
//change port number
prop.put("mail.smtp.port", "465");
prop.put("mail.smtp.socketFactory.port", "465");
prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Output:
Also you can change BodyPart accordingly i have included an html responsive template
I recommend you to visit your Google Account and generate a new Application Password , this allows your password field to be encoded and not used as plain text
Otherwise you will come up with this exception
javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required.
Hope it helped!
String host = "smtp.gmail.com";
int port = 587;
final String username = "xxxx#gmail.com";
final String password = "your password";
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", port);
Session session = Session.getInstance(props,new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}} );
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("xxxx#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("aaaa#trend.com.tw"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,\n\n No spam to my email, please!");
Transport transport = session.getTransport("smtp");
transport.connect(host, port, username, password);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
In Javamail Attachment is not displaying
I tried to send a mail with attachment
It sending and received But in received mail attachment is not displaying not display
attachment is blank and
Here the code is:
#Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol("smtp");
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setUsername("*******#gmail.com");
javaMailSender.setPassword("*********");
Properties props = ((JavaMailSenderImpl) javaMailSender).getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.mime.multipart.allowempty", "true");
javaMailSender.setJavaMailProperties(props);
return javaMailSender;
}
{
message.setSubject(mailServiceDTO.getSubject());
message.setText(mailServiceDTO.getSubject(), "text/html");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailServiceDTO.getSubject(), "text/html");
for (EmailAttachment attachment : mailServiceDTO.getAttachments()) {
message.addAttachment(attachment.getAttachmentName(), new ByteArrayResource(attachment.getAttachmentContent().getBytes()));
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(messageBodyPart);
mimeMessage.setContent(mp);
javaMailSender.send(mimeMessage);
}
you can use MimeMessageHelper in spring mail.
Example
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper mailMessage = null;
List<PathSource> pathSourceList = request.getMailAttachList();
if (pathSourceList != null && pathSourceList.size() > 0)
mailMessage = new MimeMessageHelper(msg, true);
else
mailMessage = new MimeMessageHelper(msg, false);
// ....
if (pathSourceList != null && pathSourceList.size() > 0) {
for (PathSource filepath : pathSourceList) {
ByteArrayResource stream = new ByteArrayResource(DatatypeConverter.parseBase64Binary(
filepath.getData()));
mailMessage.addAttachment(filepath.getFileName(), stream);
}
}
try {
javaMailSender.send(mailMessage.getMimeMessage());
} catch (Exception ex) {
log.error("server info {}", serverModel.toString());
throw ex;
}
Add Multiple attachments..
public static void main(String[] args) {
final String fromEmail = ""; // requires valid gmail id
final String password = "";// correct password for gmail id
final String toEmail = ""; // can be any
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); // SMTP Host
props.put("mail.smtp.port", "587"); // TLS Port
props.put("mail.smtp.auth", "true"); // enable authentication
props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
sendAttachmentEmail(session,fromEmail, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
}
public static void sendAttachmentEmail(Session session,String fromEmail, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(fromEmail));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
// Create the message body part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a multipart message for attachment
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
String filename1 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.zip";
addAttachment(multipart, filename1);
String filename2 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.log";
addAttachment(multipart, filename2);
// Send the complete message parts
msg.setContent(multipart);
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with attachment!!");
}catch (MessagingException e) {
e.printStackTrace();
}
}
private static void addAttachment(Multipart multipart, String filename) throws MessagingException
{
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
I am trying to send an email with html text and attachment using JavaMail.
However, I can only seem to make one work at a time, either it sends the html text or sends the attachment, but not both, I cant figure out how to make both.
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
final String username = "email#gmail.com";
final String password = "**********************";
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("email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("email to send"));
message.setSubject("Testing Subject");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
// Attachment
String file = "/Users/user/Desktop/file.rtf";
String fileName = "file.rtf";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent("<h1>HTML Text</h1>",
"text/html");
//HTML Text
message.setContent(multipart); //attachment
//Send
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
Here is my working code for a recent project I worked on. Hope it helps!
String from = "JohnDoe#gmail.com";
String pass = "***********";
String[] to = { "JohnDoe#gmail.com" }; // list of recipient email addresses
String subject = "Subject Line";
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "send.jpeg";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setSubject(subject);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
You're calling message.setContent twice. The second call overrides the first call, replacing the content.
See the JavaMail sample program sendfile.java for a complete working example.
The following code works only when Google's "Allow less secure apps" is ON, if that feature is off I get javax.mail.AuthenticationFailedException, how do I get it to work when that feature is OFF?
public static void main(String[] args) {
String username = "USER-NAME#gmail.com";
String password = "PASSWORD";
String to = "USER-NAME#msn.com";
Properties properties = new Properties();
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.list(System.out);
Session session = Session.getInstance(properties);
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(username));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject("This is the subject line!");
msg.setText("This is the actual message");
System.out.println("Sending message...");
Transport.send(msg, username, password);
System.out.println("Message sent!");
} catch (MessagingException ex) {
Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
try{
Properties props = new Properties();
props.put("mail.smtp.host", "ipc-smtp.bits-pilani.ac.in");
Session sess = Session.getInstance(props, null);
sess.setDebug(true);
Message msg = new MimeMessage(sess);
InternetAddress addressFrom = new InternetAddress("mymail#gmail.com");
msg.setFrom(addressFrom);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("mymail#gmail.com"));
msg.addHeader("MyHeaderName", "myHeaderValue");
msg.setSubject("Test");
msg.setContent("Yippe", "text/plain");
Transport.send(msg);
}catch(Exception exp){
exp.printStackTrace();
}
The error is javax.mail.MessagingException: 554 The mail was blocked due to zen-spamhaus RBL action
This is my college's smtp server.
I would inform your college's IT dept and they should be able to handle the issue. Although since it appears they left an open relay, maybe not.
import javax.mail.*;
import javax.mail.internet.*;
.....
public static void postMail(String[] recipients, String subject, String message, String from) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", Util.getProperty("smtpHost"));
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
//msg.addHeader("MyHeaderName", "myHeaderValue");
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
}