I am building an android app. I want to send an email from xxxxx#outlook.com. This is the code.
public void setUp
{
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
this.mailhost = "smtp.live.com";
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.port", "587");
props.setProperty("mail.smtp.starttls.enable", "true");
}
I know that user should be the whole email address. But when I used I received an email that said I should start session before send a email.
This code worked 3 times and then stopped.
What does the debug output show? What was the exact error message? Exactly what did it say in the email you received? You may need to connect with POP3 or IMAP to read mail before it will let you send mail.
You should get a session from Javamail, to create your message. Then, using a transport object, you can send it.
String host = "localhost";
int port = 443;
String user = "BruceWayne#example.org";
String password = "S3cr3tP4ss";
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(user, "Dark Knight"));
msg.setSubject("Hello Selina");
msg.setText("Do you want to have diner ?");
Transport transport = session.getTransport("smtp");
transport.connect(host, port, user, password);
transport.sendMessage(msg, msg.getAllRecipients());
Related
public static void sendEmail(String msgHeader, String msg, String emailId, String emailFrom) {
Properties props = new Properties();
props.put("mail.smtp.auth", "false");
props.put("mail.debug", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.port", port#);
props.put("mail.smtp.auth.mechanisms", "NTLM");
props.put("mail.smtp.auth.ntlm.domain", domainName);
Session session = Session.getDefaultInstance(props, null);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(emailFrom));
to = emailId;
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(msgHeader);
message.setText(msg, "utf-8", "html");
message.saveChanges();
session.getDebug();
Transport.send(message);
// Copy message to "Sent Items" folder as read
Store store = session.getStore("ntlm");
store.connect(mailServer, emailFrom, pwd);
Folder folder = store.getFolder("Sent Items");
folder.open(Folder.READ_WRITE);
message.setFlag(Flag.SEEN, true);
folder.appendMessages(new Message[] {message});
store.close();
} catch (Exception ex) {
logger.error("Error occured while sending Email !", ex);
}
}
When I try to execute the code above, i am able to send out the emails. the issue is with saving the email. I get an error (NoSuchProviderException) at the line
Store store = session.getStore("ntlm");
I have a few questions on this:-
The email sending part works without password verification with ntlm. Is it possible to save the sent email into the sent items folder without password verification. If yes then how?
session.getStore doesnt work when i use
a. smtp - exception (Invalid provider)
b. ntlm - exception (NoSuchProviderException)
what should i use here.
Thanks in advance for your help.
"ntlm" is not a type of Store, it's an authentication mechanism. The store types supported by JavaMail are "imap" and "pop3". You almost certainly want "imap". Just like sending, you're going to need to supply your username and password when connecting to your imap server.
Also, upgrade to the current version of JavaMail if possible.
I am able to send mails using SMTP. But I need to implement Oauth to avoid using password while sending mails. This can be done using accesstoken.
After lot of surfing, i got below snippet.
Properties props = new Properties();
props.put("mail.smtp.user", userEmail);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.sasl.enable", "true");
props.put("mail.smtp.sasl.mechanisms", "XOAUTH2");
props.put("mail.imaps.sasl.mechanisms.oauth2.oauthToken", oauthToken);
Session session = Session.getInstance(props);
session.setDebug(debug);
final URLName unusedUrlName = null;
SMTPTransport transport = new SMTPTransport(session, unusedUrlName);
// If the password is non-null, SMTP tries to do AUTH LOGIN.
final String emptyPassword = "";
transport.connect(host, port, userEmail, emptyPassword);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
I am struggling to connect using SMTPTransport.connect with empty password.
Can anyone help me whether I can SEND_MAILS + SMTP + OAUTH + GMAIL_ACCESS_TOKEN?
I appreciate working code suggestions. Thanks
I need to send at least 200 messages from a stretch. When the program starts, send mail successfully to 15 or 17, then I get this error:
MESSAGE ERROR:
com.sun.mail.smtp.SMTPSendFailedException: 421 4.4.2 Message submission rate for this client has exceeded the configured limit
What I can do?
CODE JAVA
public void mandarEmail(String correos, String mensaje, String asunto) {
Message message;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.port", "587");
props.put("mail.smtp.host", "pod51004.outlook.com");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("docemail#usmp.pe", "docpass");
}
});
try {
message = new MimeMessage(session);
message.setFrom(new InternetAddress("USMP - FN <documentos-fn#usmp.pe>"));
message.setSubject(asunto);
message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(correos));
message.addRecipients(Message.RecipientType.BCC, new InternetAddress[]{new InternetAddress("ivan_pro_nice#hotmail.com")});
message.setContent(mensaje, "text/html; charset=utf-8");
Transport transport = session.getTransport("smtp");
transport.connect("docemail#usmp.pe", "docpass");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
throw new RuntimeException(e);
} finally {
props = null;
message = null;
}
}
That's the server you're connecting to, and not a client issue. Here's a doc on how to parse SMTP codes from the server.
A mail server will reply to every request a client (such as your email
program) makes with a return code. This code consists of three
numbers.
In your case, you're getting 421.
You probably need to pay for a "business" account from your mail server vendor so they'll let you send more email.
if you want to send single email to 200 clients. Than u can add an array of reciever's email addresses of size upto 50.
but i you want to send different msg for each email. Then you can create a new connection to email server with a counter that counts send emails as well as it counts 15 it should create a new connection.
to test your code use mailtrap.io
I have below code to send an email to my gmail.
public class Mainclass {
public static void main(String args[]){
String host = "smtp.gmail.com";
String from = "from_address#fdsl.com";
String to = "mymail#gmail.com";
// Set properties
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.debug", true);
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("username", "mymail#gmail.com");
props.put("password", "mypassword");
// Get session
Session session = Session.getInstance(props);
try {
// Instantiate a message
Message msg = new MimeMessage(session);
// Set the FROM message
msg.setFrom(new InternetAddress(from));
// The recipients can be more than one so we use an array but you can
// use 'new InternetAddress(to)' for only one address.
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
// Set the message subject and date we sent it.
msg.setSubject("Email from JavaMail test");
msg.setSentDate(new Date());
// Set message content
msg.setText("This is the text for this simple demo using JavaMail.");
// Send the message
Transport.send(msg);
}
catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
But when i run the code i always get below the exception.
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at Mainclass.main(Mainclass.java:66)
Am i missing anything here? My password is correct. Please help me.
Thanks!
Have you set the host correctly ? Also, I don't see which ports are you using to connect. Have you set the correct ports? Is TLS the correct auth encryption for gmail ?
Please see the attached config:
'SMTP::TLS',
Host => 'smtp.gmail.com',
Port => 587,
User => 'username#gmail.com',
Password => 'password'
I want to send an email ussing an EJB but i the only thing i get in return in this exception:
java.lang.RuntimeException: javax.mail.AuthenticationFailedException: failed to connect, no password specified?
This is how my EJB looks like:
#Stateless(name = "ejbs/EmailServiceEJB")
public class EmailServiceEJB extends Authenticator implements IEmailServiceEJB {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxxx#gmail.com",
"xxxxxxx");
}
public void sendAccountActivationLinkToBuyer(String destinationEmail,
String name) {
// OUR EMAIL SETTINGS
String host = "smtp.gmail.com";// Gmail
int port = 465;
String serviceUsername = "xxxxxxx#gmail.com";
String servicePassword = "xxxxxxx";// Our Gmail password
Properties props = new Properties();
props.put("mail.smtp.user", serviceUsername);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
// Destination of the email
String to = destinationEmail;
String from = "xxxxxxx#gmail.com";
// Creating a javax.Session with the our properties
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
// From: is our service
message.setFrom(new InternetAddress(from));
// To: destination given
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject("Comfirm your account");
// Instead of simple text, a .html template should be added here!
message.setText("Welcome....... ");
Transport transport = session.getTransport("smtp");
transport.connect(host, port, serviceUsername, servicePassword);
Transport.send(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
I dont know why it keeps saying that the password is not specified? Does the SSLSocketFactory have something to do with it? Do i need to call the getPasswordAuthenticion() method somewhere, or calling the second method from my managed bean is all i need?
I don't know why your code isn't working, but you might want to take a look at this:
http://spitballer.blogspot.com/2010/02/sending-email-via-glassfish-v3.html
It shows an alternate method of configuring email in Java EE, which I think works much better. The connection details are configured at the container level, just like a container-managed database connection.
Read up on SPF and DKIM.
It's hard to know what's going wrong here, as your code is only 1/2 the needed information. The real issue is probably that your code doesn't fit your environment, and SPF and DKIM often is a reason that connecting to any public SMTP server and sending an email doesn't work.
At least after reading a little about SPF and DKIM, you'll be able to know if it is an issue in your case, or if it is not an issue in your case.