Sending Emails using smtp server host c# mvc web application - asp.net-mvc-3

Can anyone help me in fixing this issue. I know it was already asked but none of those answers helped me as I tried all of them. Anyway I hope a new solution will come up which is going to fix my problem.
It works & sends emails when I try to send emails using host smtp.gmail.com but can't send emails using host smtpout.secureserver.net. I have a valid smtp server account too.
The exception I got is here:
Unable to read data from the transport connection: net_io_connectionclosed...
web.config:
<appSettings>
<add key="fromMail" value="notification#abc.com" />
<add key="fromPassword" value="abc" />
<add key="smtpHost" value="smtpout.secureserver.net" />
<add key="smtpPort" value="465" />
</appSettings>
I also tried this in web.config:
<system.net>
<mailSettings>
<smtp from="notification#abc.com">
<network host="smtpout.secureserver.net" port="25" userName="notification#abc.com" password="abc"/>
</smtp>
</mailSettings>
</system.net>
but no luck at all...:(
Code:
public static sendMail(String toAddress, string body, string subject,string bcc,string cc)
{
String fromAddress = ConfigurationSettings.AppSettings["fromMail"];
String fromPassword = ConfigurationSettings.AppSettings["fromPassword"];
String smtpHost = ConfigurationSettings.AppSettings["smtpHost"];
String smtpPort = ConfigurationSettings.AppSettings["smtpPort"];
SmtpClient client = new SmtpClient();
client.Port = Convert.ToInt32(smtpPort);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Host = smtpHost;
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(fromAddress, fromPassword);
MailMessage mail = new MailMessage(fromAddress, toAddress);
mail.Subject = subject;
mail.Body = body;
mail.BodyEncoding = Encoding.UTF8;
mail.IsBodyHtml = true;
if(attachments != null && attachments.Count() > 0)
{
foreach(var attach in attachments)
{
mail.Attachments.Add(attach);
}
}
if(!string.IsNullOrEmpty(bcc))
mail.Bcc.Add(bcc);
if (!string.IsNullOrEmpty(cc))
mail.CC.Add(cc);
try
{
client.Send(mail);
}
catch (SmtpException exception)
{
// Console.WriteLine("Mail Sending Failed");
return "Mail Sending Failed"+ exception.Message;
}
return "ok";
}
}
Please help me guys...Thanks in advance...
Also someone in forums got the same error. He said that the problem is with his SMTP server. If the same problem in my case, how would I know that the problem lies within my SMTP server?

I am sharing my codes with you as i tried all of them too.
Here is my configuration in app.config file
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="xxx#gmail.com">
<network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" userName="xxx#gmail.com" password="xxx" />
</smtp>
</mailSettings>
And here is my c# codes (this is a console application)
Console.Write("Sending test mail...");
using (SmtpClient client = new SmtpClient())
{
try
{
client.Send("ramazandonmez#yandex.com.tr", "ramazan.donmez#euromsg.com", "Test Message Subject", "Test Message Body");
Console.WriteLine("test mail sended");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Console.ReadLine();
I hope this help.

Related

Setting mail.smtp.connectiontimeout longens requests when working with office 365

We are sending mails in an email service with org.springframework.mail.javamail.JavaMailSender via an office 365 account and SMTP and set the following parameters in application.yml:
spring:
mail:
host: ${EMAIL_HOST:smtp.office365.com}
port: ${EMAIL_PORT:587}
username: ${EMAIL_USERNAME}
password: ${EMAIL_PASSWORD}
properties:
mail:
smtp:
auth: true
connectiontimeout: 5000
timeout: 5000
writetimeout: 5000
starttls:
enable: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory
The strange thing is: if we set the connectiontimeout to 5s, the service gets a response after 5s. If we set it to 20s, the o365 responds after 20s.
My expectation is that <connectiontimeout> is the maximum amount of time, that the sending may take and not the actual time.
Funny thing is that when setting another provider than office365, connectiontimeout works as expected.
Does anyone have this issue as well and maybe know how to solve that?
Our sender service:
#PostMapping
#ResponseStatus(HttpStatus.ACCEPTED)
public void sendMail(#RequestHeader(name = "X-API-KEY", required = true) String requestApiKey, #Valid #RequestBody EmailSendRequest email, HttpServletResponse response) {
if(!apiKey.equals(requestApiKey)){
LOGGER.error("Unauthorized api key" + requestApiKey);
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
}
try {
LOGGER.info("Received request to send mail Subject=[{}] To=[{}] From=[{}]", email.getSubject(), email.getTo(), email.getFrom());
MimeMessage message = mailSender.createMimeMessage();
message.setFrom(new InternetAddress(email.getFrom().getEmail()));
message.addRecipients(Message.RecipientType.TO, toAddressArray(email.getTo()));
message.addRecipients(Message.RecipientType.CC, toAddressArray(email.getCc()));
message.addRecipients(Message.RecipientType.BCC, toAddressArray(email.getBcc()));
message.setSubject(email.getSubject());
message.setSentDate(new Date());
Multipart multipart = new MimeMultipart();
MimeBodyPart messageText = new MimeBodyPart();
messageText.setContent(email.getContent().getValue(),
email.getContent().getType() == null ? DEFAULT_CONTENT_MIMETYPE : email.getContent().getType());
multipart.addBodyPart(messageText);
addAttachments(multipart, email.getAttachments());
message.setContent(multipart);
if(message.getRecipients(Message.RecipientType.TO) != null ||
message.getRecipients(Message.RecipientType.CC) != null ||
message.getRecipients(Message.RecipientType.BCC) != null)
{
mailSender.send(message);
}
else {
LOGGER.warn("Email not send! No recipients or all ignored.");
response.setHeader("X-Ignored","true");
}
LOGGER.info("Mail Subject=[{}] To=[{}}] From=[{}] successfully sent.",email.getSubject(),email.getTo(),email.getFrom());
} catch (MessagingException e) {
LOGGER.error("Error sending mail Subject=[{}] To=[{}] From=[{}]:", email.getSubject(), email.getTo(), email.getFrom(), e);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (MailSendException mailSendException) {
Exception[] exceptions = mailSendException.getMessageExceptions();
for (Exception e : exceptions){
if (e instanceof SMTPSendFailedException && (((SMTPSendFailedException)e).getReturnCode() == 554)){
LOGGER.error("Error sending mail Subject=[{}] To=[{}] From=[{}]: This sender mail address is not allowed.", email.getSubject(), email.getTo(), email.getFrom());
throw new ResponseStatusException(HttpStatus.FORBIDDEN);
}
}
LOGGER.error("Error sending mail Subject=[{}] To=[{}] From=[{}]:", email.getSubject(), email.getTo(), email.getFrom(), mailSendException);
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR);
} catch (MailAuthenticationException e) {
LOGGER.error("Error sending mail Subject=[{}] To=[{}] From=[{}]: Wrong SMTP login credentials provided. \nMSG:{}", email.getSubject(), email.getTo(), email.getFrom(),e.getMessage());
throw new ResponseStatusException(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED);
}
}
It seems, that the SocketFactory was responsible for this behaviour. Removing the following lines from application.yml makes the application work as expected:
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory

Can't seem to send email with jhipster application

I'm trying to make a simple form that when submited sends and email to a fixed email.
I'm using spring and i've searched on how to configure the application.yml and i'm using the mailsend method that seems to have been generated with my jhipster application.
I've built my FE service to connect to the back end :
sendForm(): Observable<any>{
return this.http.post(SERVER_API_URL + 'api/sendForm', "");
}
i've built the onsubmit method to make the subscribe to the method above:
onSubmit() {
this.auth.sendForm().subscribe( data => {
console.log(data);
})
}
i've hard coded the mail resource just to mock an email to make sure its working:
#PostMapping("/sendForm")
public void sendForm() {
this.mailService.sendEmail("mymail#gmail.com","Header","texto",false,true);
}
the sendMail method that im sending the information for the mail submition is autogenerated and I believe it should be working
#Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart, isHtml, to, subject, content);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn("Email could not be sent to user '{}'", to, e);
} else {
log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
}
}
}
and heres my application-dev.yml (i'm still on dev)
spring:
profiles:
active: dev
mail:
host: smtp.gmail.com
port: 587
username: gmailuserid#gmail.com #Replace this field with your Gmail username.
password: ************ #Replace this field with your Gmail password.
protocol: smtp
tls: true
properties.mail.smtp:
auth: true
starttls.enable: true
ssl.trust: smtp.gmail.com
the errors im getting goes as follows:
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localh
ost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeo
ut -1;
All I expect is a mail with the mock i've used and I cant seem to be able to put this working.
I hope i've not made the post to long and that everything is well explained.
Thank you in advance for anyone willing to help
Apparently somewhy the properties-prod.yml wasnt being loaded to the server. I had to create a config file with all the configurations for it to work

401 Unauthorized error while trying to create shared Google App Contact

I'm trying to create a new contact using GData .Net Api.
I've got an AccessToken using the newer Google.Apis.
This acces token works alright to get,update and delete contacts, but if I try to create one I receive a 401 Unauthorized response.
This is the code I use to add my contact :
if (string.IsNullOrEmpty(FullName))
{
FullName = string.Format("{0} {1}", FirstName, LastName);
if (string.IsNullOrEmpty(FullName))
{
ThrowTerminatingError(new ErrorRecord(
new ArgumentException("Please provide a name for the contact"),
null, ErrorCategory.InvalidArgument, null));
}
}
Contact = new Contact
{
Name = new Name
{
GivenName = FirstName,
FamilyName = LastName,
FullName = FullName
},
Content = "Notes",
};
foreach (var m in Emails)
{
Contact.Emails.Add(new EMail(m));
}
RequestSettings settings = new RequestSettings(applicationName, AuthentParameters);
ContactsRequest cr = new ContactsRequest(settings);
var feedUri = new Uri(string.Format("{0}{1}/full/", Scope, Domain));
cr.Insert(feedUri, Contact));
The following atom feed is sent using POST method to http://www.google.com/m8/feeds/contacts/(my domain)/full/ :
<?xml version="1.0" encoding="utf-8"?>
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="http://schemas.google.com/g/2005">
<gd:name>
<gd:givenName>Guillaume</gd:givenName>
<gd:familyName>Davion</gd:familyName>
<gd:fullName>Guillaume Davion</gd:fullName>
</gd:name>
<gd:email address="gudavion#test.info" />
<category term="http://schemas.google.com/contact/2008#contact" scheme="http://schemas.google.com/g/2005#kind" />
<content type="text">Notes</content>
</entry>
Headers are :
Content-Type: application/atom+xml; charset=UTF-8
Authorization: Bearer ya29.(access token)
GData-Version: 3.0
Thanks to anyone who could help me.
I managed to make it work with two things :
First, changing the way I construct the feed uri :
var feedUri = new Uri(ContactsQuery.CreateContactsUri(Domain));
And second adding a label to the email :
Contact.Emails.Add(new EMail(m) { Label = "Default" });
With this, the add goes smoothly.

How to find the h2 database server is running or not from java code

I need to find whether h2 database server is running or not from java code. I have tried getStatus().isRunning(args) methods but it always shows that server is not running even if the server is running. Below is my code:
Server server = Server.createTcpServer(args);
// Find whether is server is on or not using "isRunning()" method
if (server.isRunning(false)) {
System.out.println("server is running");
} else {
System.out.println("server is not running");
}
// Find whether is server is on or not using "getStatus()" method
String statVariable = server.getStatus();
System.out.println("STATUS=" + statVariable);
System.out.println("SERVER GONNA START");
server.start();
perhaps you can send a request off to the port in question, assuming it is either WebServer or TCP server (the default ports being 8082 or 9092 respectively). You know that the call
drewmac:bin drewpierce$ java -cp h2*.jar org.h2.tools.Server
creates 3 servers and spits out something like:
TCP server running at tcp://192.168.1.3:9092 (only local connections)
PG server running at pg://192.168.1.3:5435 (only local connections)
Web Console server running at http://192.168.1.3:8082 (only local connections)
then if you call the routine to show ports on your server with listening sockets
and my call would be
drewmac:~ drewpierce$ sudo lsof -i -P | grep -i "listen"
java 81339 drewpierce 19u IPv6 0xffffff800b782ac0 0t0 TCP *:9092 (LISTEN)
java 81339 drewpierce 22u IPv6 0xffffff800b781bc0 0t0 TCP *:5435 (LISTEN)
java 81339 drewpierce 24u IPv6 0xffffff8015620800 0t0 TCP *:8082 (LISTEN)
now if you want to test the web server (http and html streams to port 80, 8082, whatever you make it, you can issue Chunk A. If you want to test the TCP server you can issue Chunk B.
Call Chunk A like java GreetingClient localhost 8082
or like java GreetingClient ec2-1-2-3-4-amaz-aws-ec2.amazon.com 8082
don't forget the 2 parameters in this test or it will barf
Chunk A:
import java.io.*;
import java.net.*;
public class GreetingClient {
public static void main(String[] args) {
// declaration section:
// mySocket: our client socket pretending to be a browser
// os: output stream
// is: input stream
Socket mySocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String serverName = args[0];
int port = Integer.parseInt(args[1]);
// Initialization section:
// btw make sure parameters are passed noting that this quick code is NOT
// Try to open input and output streams
System.out.println("*1");
try {
mySocket = new Socket(serverName,port);
os = new DataOutputStream(mySocket.getOutputStream());
is = new DataInputStream(mySocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
System.out.println("*2");
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port 80, 8082, whatever
// (what the server is listening on)
if (mySocket != null && os != null && is != null) {
try {
// pretend to be a browser and do a GET against a resource
System.out.println("*3");
os.writeBytes("GET /index.html HTTP/1.0\r\n\r\n");
System.out.println("*4");
// wait for response from webserver, dump out response for sanity check
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
// clean up:
// close the output stream
// close the input stream
// close the socket
System.out.println("*5");
os.close();
is.close();
mySocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
System.out.println("*6");
}
}
Chunk A output (for me at least):
*1
*2
*3
*4
Server: HTTP/1.1 200 OK
Server: Content-Type: text/html
Server: Cache-Control: no-cache
Server: Content-Length: 937
Server:
Server: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Server: <!--
Server: Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
Server: and the EPL 1.0 (http://h2database.com/html/license.html).
Server: Initial Developer: H2 Group
Server: -->
Server: <html><head>
Server: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
Server: <title>H2 Console</title>
Server: <link rel="stylesheet" type="text/css" href="stylesheet.css" />
Server: <script type="text/javascript">
Server: location.href = 'login.jsp?jsessionid=f3d05d9b68f4c5407054628f096ffccb';
Server: </script>
Server: </head>
Server: <body style="margin: 20px;">
Server:
Server: <h1>Welcome to H2</h1>
Server: <h2>No Javascript</h2>
Server: If you are not automatically redirected to the login page, then
Server: Javascript is currently disabled or your browser does not support Javascript.
Server: For this application to work, Javascript is essential.
Server: Please enable Javascript now, or use another web browser that supports it.
Server:
Server: </body></html>
*5
*6
A few things, clearly this is H2 output. Chunk A source code could be whittled down to about 10 lines.
Chunk B (talk jdbc to TCP jdbc server)
//STEP 1. Import required packages
import java.sql.*;
import org.h2.Driver;
public class JdbcTrial {
// JDBC driver name and database URL
//static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//static final String DB_URL = "jdbc:mysql://127.0.0.1/test";
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:tcp://localhost/~/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
System.out.println("***** 1");
Class.forName(JDBC_DRIVER);
System.out.println("***** 2");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, FirstName, LastName from people";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Chunk B output:
drewmac:~ drewpierce$ java JdbcTrial
***** 1
***** 2
Connecting to database...
Creating statement...
ID: 1, First: joan, Last: london
ID: 2, First: Sgt., Last: Corholio
Goodbye!
worked fine against mysql, mariadb, and H2, just by messing with the jdbc_driver and db_url
You could just do socket connects and not issue off data retrieval calls and really prune it down.
As far as how to do this with the H2 getStatus, I have no clue. Good luck.

sreg Yahoo problems

May you please look at the issue:
You may test Yahoo sreg at
"https://test-id.org/OP/Sreg.aspx"
ID : "https://me.yahoo.com/"
username: goughev#yahoo.com
password: paranoid
Now the problem
This code work with Google but not with Yahoo sreg,
becase response.GetUntrustedExtension() alwase returns null values for properties for Yahoo
var opUrl = LoginCore.GetProviderUrl(provider, openId);
var openIdRelyingParty = new OpenIdRelyingParty(null);
var response = openIdRelyingParty.GetResponse();
Identifier id;
if (response == null)
{
if (Identifier.TryParse(opUrl, out id))
{
try
{
var claim = new ClaimsRequest();
claim.Email = DemandLevel.Require;
claim.FullName = DemandLevel.Request;
claim.Gender = DemandLevel.Request;
claim.Nickname = DemandLevel.Require;
var request = openIdRelyingParty.CreateRequest(opUrl);
request.AddExtension(claim);
return request.RedirectingResponse.AsActionResult();
}
catch (Exception ex)
{
}
}
else
{
Model.Errors.Add(GeneralErrors.Unexpected());
return View("SignupUnTrustedOpenId");
}
}
else
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
var claimsData = response.GetUntrustedExtension<ClaimsResponse>();
if (claimsData != null)
{
email = claimsData.Email;
I am using folowing configuration:
<dotNetOpenAuth>
<openid>
<relyingParty>
<security requireSsl="false" ignoreUnsignedExtensions="false" maximumHashBitLength="256" minimumHashBitLength="160" rejectDelegatingIdentifiers="true" rejectUnsolicitedAssertions="false" requireAssociation="false" requireDirectedIdentity="false" />
<behaviors>
<add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" />
</behaviors>
</relyingParty>
</openid>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<add name="localhost" />
</whitelistHosts>
</untrustedWebRequest>
</messaging>
</dotNetOpenAuth>
I am using the latiest version 3.2.0.9177
Thank you very much for help
Vitaly
Yahoo's SREG extension support is currently only in beta. Yahoo is only willing to expose SREG support to whitelisted RPs. See here.
I went through the test-id.org test with my own Yahoo account and it worked. Your code to adding the sreg extension looks fine. So I suspect the only problem is that you're not on Yahoo's whitelist yet.

Resources