Java email - show multiple email recipients? - java

Is it possible to use Java to send an email such that I can see multiple recipients in the to/cc/bcc fields?
In other words, something like this:
From: foo#bar.com
To: user1#lol.com; user2#lol.com; user3#lol.com; user4#lol.com
Cc: admin1#lol.com; admin2#lol.com
I searched on Google but found no conclusive results, so any advice would be much appreciated.

Yes it is!
check out the javax.mail library.
Here is a code example:
class EmailSender{
private Properties properties;
private Session session;
private Message msg;
private final String SENDER_EMAIL = "your.email#whatever.com";
private final String PWD = "***********";
public void sendMail(String body) throws Throwable{
initMail();
msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("SENDER_EMAIL"));
//HERE YOU CAN CHOOSE BETWEEN TO, CC & BCC
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("Receiver Email"));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("Receiver Email2"));
msg.setRecipient(Message.RecipientType.CC, new InternetAddress("CC Email"));
msg.setRecipient(Message.RecipientType.CC, new InternetAddress("CC Email2"));
msg.setSubject("SUBJECT");
msg.setText(body);
//TRANSPORT
Transport.send(msg);
System.out.println("message sent!");
}
private void initMail(){
//PROPERTIES
//I choosed GMAIL for the demonstration, but you cant choose whatever you want.
properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
//AUTHENTICATION
session = Session.getInstance(properties, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(SENDER_EMAIL, PWD);
}
});
}
}
Don't forget to import the javax.activation library.

Yes it is.
How to do it - depends on the library you're using.

Related

Send java email without authentication/with out sender password

I'm trying to send java email without senders password. Below you can see the code. I change mail.smtp.auth from true to false. There is a override method which method name getPasswordAuthentication():
public class SendMailUtilNineThirty implements Runnable {
final private String SMTP_SERVER = "192.186.16.14";
final private String SMTP_PORT = "135";
final private String TO_EMAIL = "saman#thal.com";
final private String TO_EMAIL = "dumidu#thal.com";
final private String FROM_EMAIL = "samanchandana#thal.com";
final private String FROM_EMAIL_PASSWORD = "1qaz2wsx#";
public void sendEmail(String emailContent, String subject) {
try {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_SERVER);
props.put("mail.smtp.port", SMTP_PORT);
props.put("mail.smtp.auth", "false");
Session mailSession = Session.getInstance(props, new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_EMAIL, FROM_EMAIL_PASSWORD);
}
});
mailSession.setDebug(true);
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(FROM_EMAIL));
message.addHeader("site", "thal.com");
message.addHeader("service", "Thal Service");
message.setSentDate(new Date());
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(TO_EMAIL));
message.setSubject(subject);
How to send email without password authentication? Thanks.
In general, you need to authenticate to the mail server. If you run your own mail server, you may be able to set it up so that it doesn't require authentication, but none of the public email service vendors is going to allow that, for what I hope are obvious reasons.

Formatting an email with JavaMail in Java

So I have sent an email in Java, however It doesn't format the email as I'd like. Instead of a formatted email like this:
Hello John,
Welcome to X.
Thanks,
Johnathan.
It would show:
Hello John, Welcome to X. Thanks, Johnathan.
This is the code:
public class MailReceipt {
String receipt;
String email;
public MailReceipt(String message, String email) {
this.receipt = message;
this.email = email;
}
public void sendMessage() {
final String username = "abc123#gmail.com";
final String password = "abc123";
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");
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(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
message.setSubject("DO NOT REPLY: A receipt regarding your recent purchase.");
message.setContent(receipt, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("The mail was sent");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I am using '\n' tags in the string, however it doesn't seem to work here. Would I need to make use of html in Java? If so, could I get some examples?
You've said its content-type is HTML, so use HTML. A newline isn't significant in HTML. Try <p>, or <br/>.

How to send simple Email using Javamail?

i am creating a simple java mail program,the program is working ok and the last system print also working .but the problem is i dint received the mail in outlook.here i am using the company outlook.please some one help me.
i am attaching my code here
enter code here
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SimpleSendEmail
{
public static void main(String[] args)
{
String host = "compny host";
String from = "mail id";
String to = "usr#some.com";
String subject = "birthday mail";
String messageText = "I am sending a message using the"
+ " simple.\n" + "happy birthday.";
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("compny host", host);
props.put("mail.smtp.port", "25");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props, null);
// Set debug on the Session so we can see what is going on
// Passing false will not echo debug info, and passing true
// will.
session.setDebug(sessionDebug);
try
{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport.send(msg);
System.out.println("Sent message successfully....");
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
}
output
Sent message successfully....
"Compny host" doesn't seem like correct host. Check out this tutorial http://www.tutorialspoint.com/java/java_sending_email.htm and here you have also a few examples of sending emails in Java Send email using java
I do expect that you are using the correct host on your side.
But you are missing Username and Password.
transport = session.getTransport("smtp");
transport.connect(hostName, port, user, password);
transport.sendMessage(message, message.getAllRecipients());
or you can use the Authenticator:
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});

java: Sending failed

After multiple researches I can't succeed to send any mail with java
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.transport.protocol","smtp");
props.put("mail.smtp.host", "smtp.live.com");
props.put("mail.smtp.port", "587");
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("matr#live.fr"));
InternetAddress toAddress = new InternetAddress("matrphone#gmail.com");
msg.addRecipient(Message.RecipientType.TO, toAddress);
msg.setSubject("sujet du mail de text");
msg.setText("aaa");
Transport transport = session.getTransport("smtps");
transport.connect("smtp.gmail.com", 587,"matr#live.fr", "mypasswordcached");
transport.send(msg);
I have Exception in thread "main" javax.mail.NoSuchProviderException: No provider for smtps
I don't understand why
Anyone can help me please ?
Try the following code:
package org.kodejava.example.mail;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
public class GmailSendEmailTLS {
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static void main(String[] args) throws Exception {
//
// Email information such as from, to, subject and contents.
//
String mailFrom = "email#gmail.com";
String mailTo = "email#gmail.com";
String mailSubject = "TLS - Gmail Send Email Demo";
String mailText = "TLS - Gmail Send Email Demo";
GmailSendEmailTLS gmail = new GmailSendEmailTLS();
gmail.sendMail(mailFrom, mailTo, mailSubject, mailText);
}
private void sendMail(String mailFrom, String mailTo,
String mailSubject, String mailText)
throws Exception {
Properties config = createConfiguration();
//
// Creates a mail session. We need to supply username and
// password for Gmail authentication.
//
Session session = Session.getInstance(config, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
GmailSendEmailTLS.USERNAME,
GmailSendEmailTLS.PASSWORD
);
}
});
//
// Creates email message
//
Message message = new MimeMessage(session);
message.setSentDate(new Date());
message.setFrom(new InternetAddress(mailFrom));
message.setRecipient(Message.RecipientType.TO,
new InternetAddress(mailTo));
message.setSubject(mailSubject);
message.setText(mailText);
//
// Send a message
//
Transport.send(message);
}
private Properties createConfiguration() {
return new Properties() {{
put("mail.smtp.auth", "true");
put("mail.smtp.host", "smtp.gmail.com");
put("mail.smtp.port", "587");
put("mail.smtp.starttls.enable", "true");
}};
}
}
This example taken from: Sending email using gmail via TLS

Error while sending mails using smtp

I need to send mail from my gmail account to another. I used the following code.
String fromaddress = "xxx#gmail.com";
String password = "yyy";
String hostname = "smtp.gmail.com";
String hoststring = "mail.smtp.host";
String toaddress = "yyy#gmail.com";
String emailcontent;
Properties properties = System.getProperties();
properties.setProperty(hoststring, hostname);
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(fromaddress));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toaddress));
message.setSubject("hi");
emailcontent = "hi...";
message.setText(emailcontent);
System.out.println(emailcontent);
Transport.send(message);
System.out.println("Sent....");
}catch (MessagingException mex)
{
mex.printStackTrace();
}
But i get the error as follows...
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25
How am i to solve this. Can you please help me out.
public static void sendEmail(Email mail) {
String host = "smtp.gmail.com";
String from = "YOUR_GMAIL_ID";
String pass = "YOUR_GMAIL_PASSWORD";
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true"); // added this line
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");
// Get the default Session object.
Session session = Session.getDefaultInstance(props, null);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set sender
message.setFrom(new InternetAddress("Senders_EMail_Id"));
// Set recipient
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECIPIENT_EMAIL_ID"));
// Set Subject: header field
message.setSubject("SUBJECT");
// set content and define type
message.setContent("CONTENT", "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException mex) {
System.out.println(mex.getLocalizedMessage());
}
}
}`
I think this should do the trick.
I think you need to change the port no. 25 to 587
you can get help from
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
gmail setting help link:
http://gmailsmtpsettings.com/
Just adding few more tweaks to the question above:
Change the port to 465 to enable ssl sending.
I don't think above code will work, as you need to have an authenticator object too. As smtp also requires authentication in case of gmail.
You can do something like:
Have a boolean flag,
boolean authEnable = true; //True for gmail
boolean useSSL = true; //For gmail
//Getters and setters for the same
if (isUseSSL()) {
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.port", "465");
}
Authenticator authenticator = new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc#gmail.com", "xyz"));
}
};
if (isAuthEnable()) {
properties.put("mail.smtp.auth", "true");
session = Session.getDefaultInstance(properties, authenticator);
} else {
session = Session.getDefaultInstance(properties);
}

Categories